[Tutor] creating objects in a loop

Kirby Urner urnerk@qwest.net
Tue, 2 Apr 2002 23:22:00 -0500


On Tuesday 02 April 2002 10:45 pm, you wrote:

> The "if __name__ == '__main__':" test -- I have seen it several times
> now.  Why is this test performed?  Isn't it obvious that __name__ is
> __main__ ?  Or am I missing something....
>
>
> Erik

The convention here is to write a module that functions as a script
if executed at the command line or clicked on, but does nothing
in particular (except maybe compile) if imported as a module -- 
until you tell it to.

For example, I might have a module which includes a function to 
draw a sine wave.  When I run it as a script, I maybe go:

>>> python sinewave.py 5 20 3

thereby passing arguments to some sine function.  The module will
be considered '__main__' (top level) when it's run in this way, so 
I'll use the code block following this condition to read the arguments 
following sinewave.py, and actually draw the corresponding sine 
wave.

But if I'm in the Python shell and go:

>>> import sinewave

or do that same import at the top of some *other* module, then 
the __name__ = '__main__' condition won't be true, and no code
will actually execute, which is good, because when I import this 
way, I'm not supplying arguments to any function and I don't want 
to actually generate a sinewave.  I'll maybe do that later, by invoking 
an internal function explicitly.

Like, when you 'import math' (import the math module) you don't 
actually want it to start spitting out math results in some out-of-control 
burst.  You just want it to sit there like an open book, offering methods 
to be triggered, if and when, e.g. at the program's disgression.

The __name__ = '__main__' code block is sometimes used to 
write tests of the module's main functions.  This is in cases where
the module is really designed to function as a module.  The only
reason you'd run it as a standalone script is precisely to invoke
these tests, which will confirm or disconfirm that everything is
working properly as far as this module is concerned.

Kirby