mardi 16 janvier 2024

Should I, or can I use an: 'if __name__ == "__main__:" style construct but within an imported package or module?

The simple python file hello.py is executed in the top level environment as main:

#hello.py
def hello(input):
    print(f"hello, {input}")


if __name__ == '__main__':
    hello(input = 'world!')

I know from the docs and from previous stackoverflow Q&A, that this pattern is somewhat of a formality in standalone scripts and simple packages, but it is good practice and can be important to prevent your script from being executed if it were to be imported as a module without the if __name__ == '__main__': condition.

I now have a module foobar.py either installed or temporarily added to sys.path, and I want to import it in hello.py and then for example, execute a function or instantiate some classes it defines during the import, (or perhaps later in the main script):

#foobar.py
def foobar():
    print(f"foo bar baz")

Is it anywhere written in the docs, or implied that I can or should include the following:

if __name__ == 'foobar':
    foobar()

in a similar manner to if __name__ == '__main__': but within files for execution as an import?

Doing this to guarantee execution of the foobar() function during the import, as opposed to simply calling foobar() either at the end of the foobar.py file or after its import, from within hello.py, which would to my understanding execute the function in all cases I can see!

Similarly, should I also include a blank:

if __name__ == '__main__':
    pass

in modules and scripts which I never intend to be run as main? are there any obvious gotchas to avoid when doing this?

Aucun commentaire:

Enregistrer un commentaire