Is exec() also not used in python 2.7.1 anymore?

Peter Otten __peter__ at web.de
Tue Oct 4 04:40:05 EDT 2011


Wong Wah Meng-R32813 wrote:

> In migrating my application from python 1.5.2 to 2.7.1, one of my modules
> breaks when I import it. Here is the line where it breaks. Can I have a
> quick check if this built-in function still supported in python 2.7.1 and
> if so, what ought to be changed here? Thanks in advance for replying.
> 
>   exec('def %s(self, *args, **kw): pass'%methodStrName)
> SyntaxError: unqualified exec is not allowed in function '_exposeMethods'
> it contains a nested function with free variables

I think the message is quite explicit about the problem. You have a nested 
function along the lines:

>>> def f():
...     exec ""
...     def g(): return x
...
  File "<stdin>", line 2
SyntaxError: unqualified exec is not allowed in function 'f' it contains a 
nested function with free variables

With the current scoping rules x in the inner function may refer either to a 
local variable in f() or a global variable -- and because of the exec 
statement the compiler cannot determine which. Depending on your usecase a 
workaround may be to declare the free variable as global:

>>> def f():
...     exec ""
...     def g():
...             global x
...             return x
...     return g
...
>>> x = 42
>>> f()()
42





More information about the Python-list mailing list