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

Eric Snow ericsnowcurrently at gmail.com
Fri Nov 22 23:27:58 CET 2013


On Fri, Nov 22, 2013 at 3:02 PM, David Mertz <mertz at gnosis.cx> wrote:
> I'm not in love with the *spelling* of " if __name__=='__main__': ", but I
> very frequently use the overall pattern.
>
> Much--or even most--of the time when I write a module, I like to allow it to
> either do a minimal case of its basic functionality and/or have the module
> run some basic unit tests as a quick check against breakage.  So in contrast
> to Eric Snow, I try *to* make my files both scripts and modules.  I know
> this isn't the only possible approach, but I don't think it's bad or
> uncommon.

You're right and I think it's a good pattern too.  That is something
we do in the stdlib (and increasingly so).  It slipped my mind.  I've
also seen the idiom used for initiating tests (not that I necessarily
condone that practice), though less so in large projects.  It would be
nice if we could address the issues outlined in PEP 395.

One nice approach would be to first import the module separately, copy
the namespace into __main__, and then look for some special function
(in the module) like __main__() and run it.  That function would also
be available to use programmatically.  That's pretty similar to the
PEPs I mentioned before.  Who knows.  Maybe the time has come for the
idea.

-eric


More information about the Python-ideas mailing list