exec in a nested function yields an error

T

TP

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?

Thanks

--
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
 
A

Albert Hopkins

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,962
Messages
2,570,134
Members
46,692
Latest member
JenniferTi

Latest Threads

Top