import overwrites __name__

Peter Otten __peter__ at web.de
Sun May 10 03:33:40 EDT 2009


MRAB wrote:

> Marco wrote:
>> Hi,
>> 
>> There happened something that I do not understand. Actually I don't even
>> know how it can be possible.
>> 
>> I import a module and then the name space of the importing module seems
>> do be overwritten.
>> 
>> my_name = __name__
>> print my_name
>> print len(dir())
>> from x import y as z
>> print __name__
>> print len(dir())
>> print my_name
>> 
>> ->
>> __main__
>> 119
>> x
>> 117
>> unhandled NameError "name 'my_name' is not defined"
>> 
>> The module x is from me, and I am not aware of doing anything cruel
>> there. What evil thing can be done in its sub module that can result in
>> that strange thing?
>> 
> You'd have to show us the module. Try to make the smallest module that
> has the same effect.

$ cat x.py
import sys
globals().update(zip(*(range(110),)*2))
y = 42
print __name__
if __name__ == "__main__":
    a = b = 42
print len(dir())
from x import y as z
try:
    print my_name
except NameError, e:
    print 'unhandled NameError: "%s"' % e
    sys.exit()

$ python x.py
__main__
119
x
117
unhandled NameError: "name 'my_name' is not defined"

;)





More information about the Python-list mailing list