[Tutor] Question about __name__ global variable (Was: Tutor Digest, Vol 35, Issue 27)

Luke Paireepinart rabidpoobear at gmail.com
Tue Jan 9 14:35:10 CET 2007


raghu raghu wrote:
> i have a clarification regarding built in function,in some scripts it 
> is being used and it is give n: if _name_ == '_main_'
> why this is being used in the scripts?
The global variable __name__ is equal to '__main__' when the python 
script is run.
If the script is imported, __name__ is something other than '__main__' 
(not sure what.)
So by checking if __name__ == '__main__' we can ensure that our code can 
work both as a standalone script
and as a module.
For example:

#test-script.py
import random

def someFunction(a):
    return a * random.randrange(100)

if __name__ == "__main__":
    print "The number 42 passed to someFunction is: " + someFunction(42)

#-----

If we want to use the function someFunction from test-script.py in a 
different file,
the 'main' part won't be run.
#
import test-script

print "The number 3 passed to someFunction is: " + someFunction(3)
#-------------

if the 'if __name__ == '__main__' ' test weren't in the original 
test-script.py,
the 42 version of the print statement would be run whenever someone 
imported it.

HTH,
-Luke


More information about the Tutor mailing list