Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any explanation of exec's behavior? [duplicate]

Tags:

python

Looking for good explanation of why this code raises SyntaxError.

def echo(x):
    return x

def foo(s):
    d = {}
    exec(s, {}, d)
    return dict((x,y) for x,y in d.items())

def bar(s):
    d = {}
    exec(s, {}, d)
    return dict((x, echo(y)) for x,y in d.items()) # comment this to compile

s = 'a=1'
foo(s)

  File "test.py", line 11
    exec(s, {}, d)
SyntaxError: unqualified exec is not allowed in function 'bar' it contains a
             nested function with free variables
like image 475
Shekhar Avatar asked Dec 18 '25 23:12

Shekhar


1 Answers

In Python 2.x, exec statements may not appear inside functions that have local "functions" with free variables. A generator expression implicitly defines some kind of "function" (or more precisely, a code object) for the code that should be executed in every iteration. In foo(), this code only contains references to x and y, which are local names inside the generator expression. In bar(), the code also contains a reference to the free variable echo, which disqualifies bar() for the use of exec.

Also note that your exec statements are probably supposed to read

exec s in {}, d

which would turn them into qualified exec statements, making the code valid.

Note that your code would work in Python 3.x. exec() has been turned into a function and can no longer modify the local variables of the enclosing function, thus making the above restriction on the usage of exec unnecessary.

like image 89
Sven Marnach Avatar answered Dec 21 '25 12:12

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!