import overwrites __name__

Dave Angel davea at ieee.org
Sat May 9 05:45:46 CEST 2009


Marco 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?
>>     
>
>
> I just discovered the .pyc file for the main module is not created. When I 
> delete the old pyc and import the main module from the python shell it works 
> fine. But when I start it with "python main_module.py" the .pyc is not 
> created and it happens as shown above.
>
> So what leads to the behavior that the .pyc is not created?
>
> br
> Marco
>
>
>   
As others have said, you didn't post nearly enough of your code to 
duplicate the problem.  But I have a reasonable guess:

I suspect you've got two modules that each import the other.  If you run 
one of them as the (__main__) script from the command line, you get some 
pretty weird behavior.  To put it simply, don't ever do an import of 
"main_module" if you expect to be able to run "python main_module.py"

I suspect the underlying cause is that that module is called __name__  ( 
you know that if you've ever coded  if __name__ == "__main__"    When 
you try to import it by its actual file name, it thinks it's a new one.  
And you don't ever want two instances of the same module.  You end up 
with two copies of the global variables, and some code refers to one and 
some refers to the other, for example.

You can get into trouble any time you have mutual importing (a imports 
b., and b import a) or indirect mutual importing (a imports b, which 
imports c, which imports a).  Many languages have similar problems, as 
do Windows DLL's.  But it's even worse if your __main__ script is in the 
mix.

As Stephen suggests, write a very small script which does the initial 
import.





More information about the Python-list mailing list