On Fri, Nov 13, 2020 at 12:47 AM Matt Wozniski email@example.com wrote:
Currently, the simplest and most idiomatic way to check whether a module was run as a script rather than imported is:
if __name__ == "__main__":
People generally learn this by rote memorization, because users often want the ability to add testing code or command line interfaces to their modules before they understand enough about Python's data model to have any idea why this works. Understanding what's actually happening requires you to know that:
- the script you ask Python to run is technically a module,
- every module has a unique name assigned to it,
- a module's `__name__` global stores this unique import name,
- and "__main__" is a magic name for the initial script's module.
A new (writable) global attribute called `__main__` would simplify this case, allowing users to simply test
It would behave as though
__main__ = (__name__ == "__main__")
is executed in each module's namespace before executing it.
Benefits: One incantation becomes slightly shorter. Costs: Forever have to maintain both ways of doing things.
The __name__ version of the idiom is going to stick around (there's no point breaking people's code), so there's going to be two ways to spell the exact same thing. Both are still going to have to be memorized (you have to get exactly two underscores either side), and while the alternate IS shorter, it's not that much of a benefit.
I actually don't use the "if name is main" idiom all that often. The need to have a script be both a module and an executable is less important than you might think. In a huge number of cases, it's actually better to separate out the library-like and script-like portions into separate files, or some other reorganization. It just isn't that much benefit, especially since the longhand will be essential for compatibility with all versions up to X.Y when the shorthand would get added.