Why I need to declare import as global in function

Duncan Booth duncan.booth at invalid.invalid
Tue Nov 29 08:55:00 EST 2005


Peter Otten wrote:

>>      Traceback (most recent call last):
>>        File "../tu.py", line 21, in run_tu
>>          execfile( filename )
>>        File "TU_05_010.py", line 8, in ?
>>          import TU_05_tools
>>        File "./TU_05_tools.py", line 4, in ?
>>          f()
>>        File "./TU_05_tools.py", line 2, in f
>>          print math.pi
>>      NameError: global name 'math' is not defined
>> 
>> I have remarq that this problem is raised when I execute code in an
>> imported module (during importation)
>> 
>> I think I will be able to isolate it and have a simple sample soon ....
> 
> Random guess: change the execfile() call to
> 
> execfile(filename, globals())
> 
> or
> 
> exec file(filename).read()

That is unlikely to help. The execfile target seems to have been 
TU_05_010.py, but the file which cannot access math is TU_05_tools.py 
accessed by a normal import, so adding some globals to the execfile call 
won't really do anything useful.

Isn't it fun trying to guess the problem in the absence of the code?



More information about the Python-list mailing list