import overwrites __name__

Dave Angel davea at ieee.org
Sun May 10 14:21:03 EDT 2009


Scott David Daniels wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">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
>
> </div>
>
I already said this before - don't ever import the file you're using as 
a script.  Now that we have real names for these files, I can say it 
more strongly.

If you use "import x"    or its variant "from x import..."   then *DO 
NOT* run x.py as your main script.

You must have a separate script file that you run, and that nobody tries 
to import.

Now, once you get past that problem, you'll probably have others.  Why 
on earth would you try to import a module from itself? The line:
   from x import y as z

is probably equivalent to  z=y





More information about the Python-list mailing list