Python: Weird "nameerror: Name ... Is Not Defined" In An 'exec' Environment
Solution 1:
This is just a guess, because you haven't shown us enough code, and what you've shown us doesn't actually reproduce the problem, but…
If you're doing this exec
inside a function, then locals()
and globals()
are going to be different. In which case the code will be executed as if it were inside a class definition. So, it'll be (sort of) as if you did this:
class_:
from x import X
classY(X): # does not crash here, ...def__init__(self):
X.__init__(self) # ... but here
foo=Y()
del _
(I previously thought you'd have to also be doing something like Y()
outside the exec
, but user2357112's answer convinced me that isn't necessary.)
If that's your problem, you may be able to fix it by just calling exec(code, globals(), globals())
or exec(code, locals(), locals())
. (Which one is appropriate, if either, depends on what you're actually trying to do, of course, which you haven't told us.)
Solution 2:
From the exec
documentation:
If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.
There are good reasons for this, which I won't go into here.
Functions defined in a class definition don't look in the scope of the class definition for variable resolution. When you exec
your code
, it's actually executed like this:
classDummy:
from x import X
...
classY(X):
def__init__(self):
X.__init__(self)
...
foo=Y()
That means this function:
def__init__(self):
X.__init__(self)
doesn't see this variable:
from x import X
even though this bit:
class Y(X):
does see it.
Post a Comment for "Python: Weird "nameerror: Name ... Is Not Defined" In An 'exec' Environment"