exec behaviour

N

N. Pourcelot

Hello,
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

Now, suppose I would like to make exactly the same without exec :

class A:
def __init__(self):
self.n = 3
self.m = None
def h(self, ini):
n = self.n
m = self.m
if ini:
def m(x): return n+x
self.m=m
else: return m(7)

je lance :
obj = A()
obj.h(1)
obj.h(0)

This time, it works fine !!!

If I knew why the first doesn't work, and the second does, it would be a
great help for me for my program...

Thank you very much !
 
F

Fredrik Lundh

N. Pourcelot said:
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>
 
N

N. Pourcelot

Thanks for you reply.
I added locals() to my exec statment, so it worked, but I wasn't so sure
about my interpretation of the problem.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top