if __name__ == 'main':

Patrick Down patrick.down at gmail.com
Tue Mar 20 13:13:16 EDT 2007


On Mar 20, 11:49 am, "gtb" <goodTweetieB... at hotmail.com> wrote:
> Hi,
>
> I often see the following 'if' construct in python code. What does
> this idiom accomplish? What happens if this is not main? How did I get
> here if it is not main?

A quick example demonstrates the usage:

C:\code>type temp.py


print "Module name is",__name__

if __name__ == "__main__":
    print "I was not imported"
else:
    print "I was imported"

C:\code>python temp.py
Module name is __main__
I was not imported

C:\code>python
Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import temp
Module name is temp
I was imported





More information about the Python-list mailing list