Why I need to declare import as global in function

Peter Otten __peter__ at web.de
Tue Nov 29 13:46:35 CET 2005


didier.doussaud at gmail.com wrote:

> the error message :
> 
> EXCEPTION RAISED::
> 
>      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()

If one of the above works, a minimal example of what happens could be

file("tmp.py", "w").write("""
import math
""")

def f():
    execfile("tmp.py")
    print locals()["math"].pi # 3.14159265359
    print math.pi             # Error, math looked up in the global
namespace

f()

execfile() puts symbols into the local namespace but keeps the compiler
clueless because it's just an ordinary function, whereas exec triggers the
generation of slightly different bytecode for the enclosing function.

Peter




More information about the Python-list mailing list