Sorry, forgot to use "reply to all"

---------- Forwarded message ---------
From: André Roberge <andre.robe...@gmail.com>
Date: Sat, Nov 14, 2020 at 11:06 AM
Subject: Re: [Python-ideas] Re: Global flag for whether a module is __main__
To: Steven D'Aprano <st...@pearwood.info>




On Sat, Nov 14, 2020 at 10:45 AM Steven D'Aprano <st...@pearwood.info>
wrote:

> On Sat, Nov 14, 2020 at 08:10:44AM -0400, André Roberge wrote:
>
> > > What if you import the `__main__` module? What does `__imported__` say
> > > now, and how do you check for "running as a script" if `__main__` has
> > > imported itself -- or some other module has imported it?
> > >
> >
> > Running a module (no matter what its name is) from a command line would
> set
> > __imported__ to False for that module.
> > Using import some_module (or __import__("some_module")) would set
> > some_module.__imported__ to True.
>
> Do you understand that a module can be both run and imported at the
> same time?
>
>
>     # example.py
>     import __main__
>     print(__main__.__file__)
>
> As others have mentioned, many beginners are thoroughly confused by the
meaning of the idiom

if __name__ == "__main__":
    ...

The idea behind the name  __imported__ (and, I gather, somewhat similar to
the original suggestion of __main__ that started this thread) is to reduce
such confusion.

For what I had in mind, the semantic would be the same as though the
following was inserted at the top of the module:

__imported__ = True
if __name__ == "__main__":
     __imported__ = False

André


> If you save that snippet as "example.py", and then run it:
>
>     python3 example.py
>
> you have an example of a module that is being run and imported
> simultaneously.
>
>
> --
> Steve
> _______________________________________________
> 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/MK4ZOWGY7CGJT22RTP2G7ZMUREE32CAB/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
_______________________________________________
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/VKHAHZPQAXULQE7RYNAWVWGRLFDSG5OE/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to