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

Antoine Pitrou solipsis at pitrou.net
Mon Nov 25 17:05:18 CET 2013


On Tue, 26 Nov 2013 01:12:21 +1100
Steven D'Aprano <steve at pearwood.info> wrote:
> 
> (1) Keep the status quo. 

+1.

The status quo has another benefit: it teaches beginners about __name__
and, with it, the fact that many Python objects have useful
introspection data.

> (3) Add an is_main() function to simplify the idiom to:
> 
> if is_main():
>     ...
> 
> Pros: 
> 
> - the magic of deciding whether we're running in the main module 
>   is hidden behind an abstraction layer;
> 
> - even more easily understood than the current "if __name__" idiom;
> 
> - easily backported.
> 
> Cons:
> 
> - one more built-in.

Other con: the is_main() implementation would have to be hackish (use
of sys._getframe() or a similar trick).

I'm personally -0.5.

> (5) A decorator-based solution.

-1. Much too complicated for a simple need.

Regards

Antoine.




More information about the Python-ideas mailing list