#🔒 if __name__ == __main__

11 messages · Page 1 of 1 (latest)

agile rune
#

I have seen a number of pysters recommend using if name == main statements for modules and packages, but I don't see it in practice all the often. I know that direct call benefits of using it, but is there any adverse overhead for including it in every imported module? (complexity, performance, maintenance, etc). Thoughts?

keen impBOT
#

@agile rune

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

potent geyser
#

even if you have multiple import statements, you don't actually import the package multiple times
python caches the package the first time you imort, then consecutive calls just go to a look up table
e.g.

# a.py
if __name__ == "__main__":
    pass
else:
    print("hey")

# b.py
import a
import a
import a
import a
import a
import a
```only 1 `hey` gets printed
tough sapphire
#

so that if is there to make sure the code is ran only when it's called as the main program

#

another usecase is to have callable modules

#

i.e. how python3 -m sqlite3 works

#

although there you might often find __main__.py used instead

keen impBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.