On Fri, Nov 13, 2020 at 12:47 AM Matt Wozniski <godlyg...@gmail.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: > > 1. the script you ask Python to run is technically a module, > 2. every module has a unique name assigned to it, > 3. a module's `__name__` global stores this unique import name, > 4. 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 > > if __main__: > > 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. -0.9. 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. ChrisA _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/VFEQO3BKQ3G2GKGBBY7GTOC5UN724Y3X/ Code of Conduct: http://python.org/psf/codeofconduct/