import overwrites __name__

Piet van Oostrum piet at cs.uu.nl
Sun May 10 11:10:50 EDT 2009


>>>>> 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.
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list