[Tutor] '__name__' == '__main__'

Alan Gauld alan.gauld at btinternet.com
Tue Feb 21 09:35:49 CET 2012


On 21/02/12 04:55, Michael Lewis wrote:
> I am back to being confused. I just tried running the module without
> first importing it, and it worked just fine. How do I do this properly
> to where the module only runs if I import it?

Whoooah!
That paragraph is so full of ambiguities as to be meaningless.
What exactly did you do to "run it without first importing it"?
And what happened that was "just fine"?
And what do you expect when you say "properly"?
What is it that you are expecting to happen? And what does happen?

The module always runs when you import it regardless of whether you have 
an if statement, the only thing that changes is the value of __name__. 
There is no other magic, the if statement is is just
like any other piece of Python code.

But, the file will also run if you execute it, again the only difference 
is the value of __name__. When you import the file it
is run with __name__ set to the filename. When you execute the file
__name__ is set to "__main__"


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list