import overwrites __name__

Scott David Daniels Scott.Daniels at Acm.Org
Sun May 10 13:06:04 EDT 2009


Piet van Oostrum wrote:
>>>>>> Peter Otten <__peter__ at web.de> (PO) wrote:
> 
>> PO> $ cat x.py
>> PO> import sys
>> PO> globals().update(zip(*(range(110),)*2))
>> PO> y = 42
>> PO> print __name__
>> PO> if __name__ == "__main__":
>> PO>     a = b = 42
>> PO> print len(dir())
>> PO> from x import y as z
>> PO> try:
>> PO>     print my_name
>> PO> except NameError, e:
>> PO>     print 'unhandled NameError: "%s"' % e
>> PO>     sys.exit()
> 
>> PO> $ python x.py
>> PO> __main__
>> PO> 119
>> PO> x
>> PO> 117
>> PO> unhandled NameError: "name 'my_name' is not defined"
> 
> This is perfectly normal. python x.py command runs normally (although
> the globals().update is a very weird thing to do), until the from x
> import y command. Then x.py is loaded again but now as the module 'x'
> instead of '__main__'. Python doesn't know it's the same file, and
> actually it doesn't want to know. It only knows it when you do import
> twice on the same file. Not when you run it as a main script first and
> then imports it. **This is a thing you shouldn't do**.
> There are now two namespaces: one for __main__ and one for x. These are
> distinct and have no relationship. 
> 
> The reason that the first number is 119 and the second is 117 is that
> while importing x the variables a and b are not created.
After a bit more boiling down:

x.py:

import sys
y = 42
if __name__ == "__main__":
     a = b = 42
print __name__, 'size', len(dir())
from x import y as z
print __name__, 'size', len(dir()), 'completed import of', z
try:
     print my_name
except NameError, e:
     print '%s found unhandled NameError: "%s"' % (__name__, e)
     sys.exit()

produces:
__main__
__main__ size 8
x
x size 6
x size 7 completed import of 42
x found unhandled NameError: "name 'my_name' is not defined"

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list