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

Philipp A. flying-sheep at web.de
Sun Nov 24 17:26:54 CET 2013


i’m all for a special method name or decorator, because of the namespace
issue.

once you do more on your main function than print(‘Hello World’), say
define variables, you tend to do:

def main():
    ...
if __name__ == '__main__':
    main()

in order not to pollute the namespace of the module.

if __main__:
    ...

looks nice, but will result in the same definition as the old behavior for
that reason.

so i’d propose one of the following API-wise:

def __main__():
    ...
@mainfunctiondef main():
    ...

and implementation-wise, both should result in the function being called
once the module is loaded, no matter where it is in the code. and both
would AFAIK need a change to the module loader as AFAIK you can’t create a
after-load hook for a module (if you can, the decorator would work without
a change to the loader)


2013/11/24 Gregory P. Smith <greg at krypto.org>

>
> On Sat, Nov 23, 2013 at 7:35 PM, Greg Ewing <greg.ewing at canterbury.ac.nz>wrote:
>
>> Haoyi Li wrote:
>>
>>> Import hooks don't work with __main__ =( I spent a while trying to get
>>> it to work when working on MacroPy, to no avail.
>>>
>>
>> It's hard to see how they could. How would you *install*
>> an import hook before __main__ got imported?
>
>
> *Don't do this*... but you can abuse sitecustomize:
> http://docs.python.org/3.4/library/site.html
>
> -gps
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20131124/87cf495f/attachment.html>


More information about the Python-ideas mailing list