import overwrites __name__

Scott David Daniels Scott.Daniels at Acm.Org
Fri May 8 20:35:34 EDT 2009


Glenn Hutchings wrote:
> On Fri, 08 May 2009 19:14:52 +0200, Marco wrote:
> 
>> 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"
> 
> Interesting.  Here's one possibility for the contents of module x.py:
> 
> import sys
> del sys.modules['__main__'].my_name
> y = 42
> 
> I can't think of any other way apart from grovelling through sys.modules.

OK, here's one way to see more detail:
     import sys
     my_name = __name__
     pre = set(sys.modules), set(dir())
     from x import y as z
     post = set(sys.modules), set(dir())
     print 'Modules added: %s, removed: %s' % (
                post[0] - pre[0], pre[0] - post[0])
     print 'Globals added: %s, removed: %s' % (
                post[1] - pre[1], pre[1] - post[1])

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



More information about the Python-list mailing list