On Thu, Nov 12, 2020 at 9:46 AM Matt Wozniski <godlygeek@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.

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.

Thus, 

if not __imported__:

would behave the same as the proposed

if __main__:


André


 

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 -- python-ideas@python.org
To unsubscribe send an email to python-ideas-leave@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/CUNE3Y2YSQQSTXFITSXKFRVPO6EM2DV7/
Code of Conduct: http://python.org/psf/codeofconduct/