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

Andrew Barnert abarnert at yahoo.com
Mon Nov 25 18:27:18 CET 2013


On Nov 25, 2013, at 8:05, Antoine Pitrou <solipsis at pitrou.net> wrote:

> 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.

This is a great point. 

In fact, I even took advantage of this fact a few days ago, explaining the __self__ attribute on (bound) methods by saying "Almost everything in Python has useful attributes, like the __name__ attribute on modules that you use every day", so I'm not sure why I didn't notice this benefit until you pointed it out... But I'm glad you did. 

>> (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).

Agreed. If Python had a (non-hacky) way to declare a variable as coming from the caller's namespace instead of the defining namespace this would be a great answer. But Python doesn't (and probably shouldn't) have any such feature, and a function that everyone learns as a novice that implies such a feature exists is probably a bad idea.

> I'm personally -0.5.
> 
>> (5) A decorator-based solution.
> 
> -1. Much too complicated for a simple need.
> 
> Regards
> 
> Antoine.
> 
> 
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas


More information about the Python-ideas mailing list