exec behaviour

N. Pourcelot baudelaire_2c at yahoo.fr
Fri Nov 4 11:40:05 EST 2005


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 !



More information about the Python-list mailing list