[Tutor] creating objects in a loop

alan.gauld@bt.com alan.gauld@bt.com
Wed, 3 Apr 2002 17:11:30 +0100


> 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....

The name is only __main__ when its the top level script. 
If the file is being imported by anither file then it 
will have its name set to the module name.

ie If we have modules spam and eggs where spam imports eggs
spam  creates a function s() and eggs a function e().

#### eggs.py
def e(): print 'eggs'

if __name__ == "__main__": e()


#### spam.py
import eggs

def s(): 
	print spam
	print eggs.__name__

if __name__ == "__main__": s()

##############

Now if we run 
$ python spam.py

Its name will be __main__ but egg's name will be eggs.
We see:

spam
eggs

If we run 

$ python eggs.py

Now its name will be __main__ and we see:

eggs


Thus Python provides us with the means to use the 
same file as both a program that can be run or a 
module that can be imported with no bad effects.

Alan G.