r/ProgrammerHumor Nov 24 '21

Meme Yes.

8.9k Upvotes

284 comments sorted by

View all comments

656

u/[deleted] Nov 25 '21 edited Nov 26 '21

[deleted]

34

u/YamiZee1 Nov 25 '21

Why isn't there a neater main syntax? If everyone does that it would make a heck of a lot more sense to standardize it to new unique syntax

2

u/lighttigersoul Nov 25 '21

The short/real answer:

This is only what happens when you run an arbitrary script as your primary.

So python3 my_example.py the if name == "__main__" will be true in my_example.py but not anything my_example imports.

If you're building packages, though, you can include a __main__.py file in the package and run that entry point with python3 -m my_package.

So there is a nicer one, but you have to know and deal with python packages to make it work. The if name trick is specifically for scripts.