[Tutor] How does it function

Terry Carroll carroll at tjc.com
Thu Mar 30 03:05:23 CEST 2006


On Wed, 29 Mar 2006, Steve Nelson wrote:
> On 3/29/06, Kaushal Shriyan <kaushalshriyan at gmail.com> wrote:
> >
> > Just wanted to know the detailed explanation about the below statement
> >
> > if __name__ == "__main__":
>
> Simple answer - any python program you write is effectively a
> 'module'.  Modules have an attribute __name__.  If you've imported the
> module from elsewhere, the __name__ is set to the name of the module,
> otherwise it is __name__.

I don't mean to nitpick, but I see Steve had a small but crucial slip
here.  I think he means, " If you've imported the module from elsewhere,
the __name__ is set to the name of the module, otherwise it is "__main__".

> This means that you can write a test that says:If the code we're
> trying to run is the main program, go ahead and start running the
> functions we need.

Yes; a typical usage is:

[bulk of program is here, in the form of one or more callable methods]

if __name__ == "__main__":
   [stuff]

Where "[stuff]" is either code to invoke your callable methods as you'd 
normally have the program run, or, (commonly for modules intended to be 
imported and used) code to test the module and confirm that a number of 
predetermined invocations with predetermined expected output actually 
produce that output.



More information about the Tutor mailing list