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

Rob Cliffe rob.cliffe at btinternet.com
Sat Nov 23 00:47:57 CET 2013


On 22/11/2013 22:27, Eric Snow wrote:
> 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.
Yes.  Having functionality and some test of that functionality in the 
same module simplifies file organisation/maintenance.  The test 
typically also provides extra documentation of the functionality ("this 
is how you use it").

Rob Cliffe


More information about the Python-ideas mailing list