exec behaviour

Fredrik Lundh fredrik at pythonware.com
Fri Nov 4 16:07:32 EST 2005


N. Pourcelot wrote:

> I can't understand some specific behaviour of the exec statment.
>
> For example, say that I create such a class A :
>
> class A:
>     def __init__(self):
>         self.n = 3
>         self.m = None
>     def h(self, ini):
>         n = self.n
>         m = self.m
>         if ini: exec("def m(x): return n+x"); self.m=m
>         else: m(7)
>
> Now :
> obj = A()
> obj.h(1)
> obj.h(0)
>
> I get :
>
> Traceback (most recent call last):
>   File "<input>", line 1, in ?
>   File "<input>", line 9, in h
>   File "<string>", line 1, in m
> NameError: global name 'n' is not defined

exec only supports local and global scopes; the "n" inside the exec statement
is a not a local, so it's assumed to be a global variable.

(Python's lexical scoping requires the compiler to look for free variables in inner
scopes before generating code for the outer scope; it cannot do that for exec, for
obvious reasons).

</F> 






More information about the Python-list mailing list