[Tutor] if __name__=='__main__' test

Sean 'Shaleh' Perry shalehperry@attbi.com
Thu, 07 Mar 2002 14:04:05 -0800 (PST)


On 07-Mar-2002 Bruce Gollng wrote:
> Help please.  I've been studying several books and online tutorials and have
> been consistently stumped with the  ..  if __name__ == '__main__': test.  No
> matter when I check __name__ always eq __main__.  So why is this a
> programming benefit?
> tks
> Bruce Golling (bwgolling@attbi.com)
> 

the __name__ of a module is set to one of two things.  '__main__' means the
modules is run as a .py script by python.  Otherwise it is set to the module's
name.

one:/tmp$ python foo.py
I am running
one:/tmp$ python
Python 2.1.2 (#1, Jan 18 2002, 18:05:45) 
[GCC 2.95.4  (Debian prerelease)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> import foo
>>> foo.whereami()
foo
>>>

foo.py is simply:

def whereami():
  print __name__

if __name__ == '__main__':
  print "I am running"