On Sun, 29 Apr 2007 07:32:44 -0400, Bart Willems wrote:

> gtb wrote:
>> appear at the end of many examples I see. Is this to cause a .class
>> file to be generated?
> This might be obvious, but no one else mentioned it: the Python 
> interpreter cannot execute code that it hasn't compiled yet, which is 
> why the "if __name__ ..." code is always at the end of the module - to 
> guarantee that the entire file is scanned first.

Nonsense.

Here's my "test.py":

%%%%%

x = 42

if __name__ == "__main__":
    print "x has value", x
    x = 23

print "now x has value", x

%%%%%

It works just as you would expect:


$ python test.py
x has value 42
now x has value 23

And when you import it:

>>> import test
now x has value 42


There is nothing, absolutely nothing, magic about the idiom 
if __name__ == "__main__". It is just an if block, like any other if
block. If you still aren't convinced, try this one:


%%%%%

x = 42

if __name__ == "__main__":
    print "x has value", x
    print "y has value", y

y = 43

%%%%%



-- 
Steven D'Aprano 

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to