[Python-ideas] Replacing the if __name__ == "__main__" idiom (was Re: making a module callable)
Chris Angelico
rosuav at gmail.com
Mon Nov 25 23:26:27 CET 2013
On Tue, Nov 26, 2013 at 9:12 AM, Ron Adam <ron3200 at gmail.com> wrote:
> I was thinking that __main__ would be set to "__main__" first, then when the
> main module is loaded, it's __name__ attribute set to __main__ rather than
> "__main__". Exactly as the first example above.
I thought you were describing assigning a particular string to
__name__, which is where the problem would come from. If it's being
set to "whatever's in __main__", then yes, your description is correct
and it's safe.
OTOH, what you now have is:
# standard idiom, everyone knows this works
if __name__ is __main__:
# use of actual thing: it's a string
print(__name__)
# everywhere else, this is the wrong thing to do:
if input() is "yes": do_dangerous_stuff()
So now you have to explain why it's right to use 'is', but only with
these things, which are magical. Possibly the easiest would be to
guarantee that __main__ and __name__ are sys.intern()'d, which could
then lead into an explanation of interning rather than an explanation
of magic.
ChrisA
More information about the Python-ideas
mailing list