newb: What is the purpose of if __name__ == "__main__":

J

johnny

What is the purpose of
if __name__ == "__main__":

If you have a module, does it get called automatically?
 
R

Robert Kern

johnny said:
What is the purpose of
if __name__ == "__main__":

If you have a module, does it get called automatically?

http://docs.python.org/lib/module-main.html

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
 
S

Soni Bergraj

johnny said:
What is the purpose of
if __name__ == "__main__":

If you have a module, does it get called automatically?

It is a common pattern to make one and the same source file usable as a
program and as a module. When you import some python module its
__name__ is never "__main__". When you run a python script __name__ is
always "__main__". This way you can control what shall happen when you
run the source file as a standalone program.

To put it simple: Everything in the `if __name__ == "__main__":` block
is only executed when you run the source file as a program.

Hope that helps,
 

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

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top