On Thu, Nov 12, 2020 at 9:46 AM Matt Wozniski firstname.lastname@example.org 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.
As a goal of making it even more obvious what the (new) idiom mans, I would suggest a variable named __imported__ with the opposite value to what is proposed.
if not __imported__:
would behave the same as the proposed
Because this would be writable, I don't see any backwards compatibility issues. It wouldn't negatively impact any modules that might already be defining `__main__` (for example, by doing `import __main__`). They'd simply redefine it and go on using the `__main__` module as they always have. And a package with a `__main__.py` does not have a `__main__` attribute.
It would be easier to teach, easier to learn, and easier to memorize, and a nice simplification for users at the cost of only very slightly more complexity in the data model. _______________________________________________ Python-ideas mailing list -- email@example.com To unsubscribe send an email to firstname.lastname@example.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://email@example.com/message/CUNE3Y... Code of Conduct: http://python.org/psf/codeofconduct/