Skip to content Skip to sidebar Skip to footer

Any Explanation Of Exec's Behavior?

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())

Solution 1:

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.

Solution 2:

You probably try to write python 2.x code using a python 3.x manual. With Python 3.2 I don't get this error and in Python 2.7 the exec syntax is quite different.

Post a Comment for "Any Explanation Of Exec's Behavior?"