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

Antoine Pitrou solipsis at pitrou.net
Sun Nov 24 23:48:22 CET 2013


On Mon, 25 Nov 2013 08:21:26 +1000
Nick Coghlan <ncoghlan at gmail.com> wrote:
> On 25 Nov 2013 07:26, "Antoine Pitrou" <solipsis at pitrou.net> wrote:
> >
> > On Sun, 24 Nov 2013 11:10:43 -0800
> > Guido van Rossum <guido at python.org> wrote:
> > > Haven't followed all of this, but perhaps the simplest thing would be to
> > > define a new builtin function that returns True in the namespace of the
> > > main module and false everywhere else. It could be implemented by
> pulling
> > > '__name__' out of the caller's local namespace and comparing it to
> > > '__main__'. We could name this function __main__(), or perhaps less
> > > dramatic, is_main(). Then you could write
> > >
> > > if is_main():
> > >     <do your main code>
> >
> > Why not make it so that a module function named __main__, if it exists,
> > gets executed when the module is run as a script?
> 
> I consider the fact that the semantics of __main__ execution are largely
> the same as those of any other module import to be a feature rather than a
> bug.

Yes, I'm quite happy with the current idiom myself. I was merely
suggesting this in case many people start opposing the statu quo and
start demanding another idiom :-)

Regards

Antoine.




More information about the Python-ideas mailing list