exec in a nested function yields an error

Albert Hopkins marduk at letterboxes.org
Tue Jan 13 10:37:17 EST 2009


On Tue, 2009-01-13 at 16:13 +0100, TP wrote:
> Hi everybody,
> 
> Try the following program:
> 
> ####################
> def f():
>     def f_nested():
>         exec "a=2"
>         print a
> f()
> ####################
> 
> It yields an error.
> $ python nested_exec.py
>   File "nested_exec.py", line 3
>     exec "a=2"
> SyntaxError: unqualified exec is not allowed in function 'f_nested' it is a
> nested function
> 
> What is the problem?
> Why?
> 

I believe because in the above example what namespace is local for the
exec is ambiguous so you need to specify it explicitly.

Also, and I'm sure you know this, exec can be dangerous and should be
used wisely/rarely.

 




More information about the Python-list mailing list