[Python-ideas] Replacing the if __name__ == "__main__" idiom (was Re: making a module callable)

Barry Warsaw barry at python.org
Mon Nov 25 23:16:03 CET 2013


On Nov 25, 2013, at 01:22 PM, Guido van Rossum wrote:

>Still only -0 from me, mostly because of the first two of your items, and
>because it just replaces one kind of magic with another.

Just to continue playing along (since I have no problem with the current
idiom), I do like Nick's shadowing idea.

I guess what I don't like about is_main() is that it's a function call, and is
two words separated by an underscore.  I have no technical arguments against
it, just that to me it doesn't look as pretty.  And also, I guess, a function
call seems a little more magical than checking an attribute value.  What does
the function *do*?  OTOH, I guess a shadowed builtin variable is a little
magical too, but maybe a touch more transparent magic. ;)

>But mostly I don't see why it has to involve a __dunder__ name (other
>reminding the reader of the old idiom). The reason for using __dunder__
>style for __name__ and '__main__' was clear: they impose on namespaces that
>are nominally the user's (__name__ is a global variable, the value
>'__main__' is a module name, we don't want to interfere with a user-defined
>global variable named 'name' nor with a user-defined module named 'main').
>But we don't need the same kind of caution for builtins (if the use defines
>a variable is_builtin that variable wins).

I don't think we could use a builtin called "main", because you'd get some
confusions like this:

def main():
    # blah blah

if main:
    main()

OTOH, maybe that's actually kind of cute.  It means a builtin `main` could be
False and no implicit shadowing would be necessary.  I guess some folks don't
like to call their main function main() so maybe that wouldn't work for them,
but it's not like the old idiom would go away.

Except: you surely could have main() functions in other modules which aren't
run as scripts, so that would break.  Okay, never mind.

But I do think that this means any magic builtin would have to be dundered.
Even is_main() could be a legitimate name for a function in an existing
module.

-Barry
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20131125/01286b7b/attachment.sig>


More information about the Python-ideas mailing list