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

Nick Coghlan ncoghlan at gmail.com
Mon Nov 25 11:20:23 CET 2013


On 25 November 2013 17:19, Cameron Simpson <cs at zip.com.au> wrote:
> On 24Nov2013 17:26, Philipp A. <flying-sheep at web.de> wrote:
>> 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.
> [...]
>
> This is what I do, almost word for word. When I do this, the main()
> function is the first function in the module and the code at the
> bottom goes:
>
>   if __name__ == '__main__':
>       import sys
>       sys.exit(main(sys.argv))
>
> This make the main() function obvious when looking at the code, and makes
> things work intuitively on the command line, with a meaningful exit status.
>
> Modules without a main() run unit tests and I have an aspirational goal to
> fold a selftest mode into the module with a main().
>
> A magic name? It seems a little overkill if the code is written in a fashion
> like the above: the main() is obvious.

So, rather than the low level "is_main", perhaps a higher level
builtin would be appropriate?

>>> def run_if_main(f):
...     import sys
...     if sys._getframe(-1).f_globals.get("__name__") == "__main__":
...         sys.exit(f(sys.argv))
...

Starting to get a little too magical for my taste at that point,
although with a small tweak (to return "f" in the "not main" case) it
*does* allow the idiom:

    @run_if_main
    def main(argv):
        ...

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list