if __name__ == 'main':

G

gtb

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?

Thanks,

gtb

==============================================

if __name__ == 'main':
myQuest('myQuest').Run()
 
G

Grant Edwards

I often see the following 'if' construct in python code. What does
this idiom accomplish?

It checks to see if the file is being run as the "main"
program, and does something if that is so.
What happens if this is not main?
Nothing.

How did I get here if it is not main?

By importing the file.
 
F

Facundo Batista

gtb wrote:

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?
...
if __name__ == 'main':
myQuest('myQuest').Run()

This idiom is for executing the code if you're running the .py directly,
or doing nothing if you're just "import"ing the module.

Take note, that when you import a module, __name__ gets the module name.

Regards,
 
P

Patrick Down

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.Module name is temp
I was imported
 
G

gtb

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


Thanks, all! Makes great sense.


Teas all 'round the canteen now,

gtb
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top