strange SyntaxError

A

Attila Szabo

Hi,

I wrote this sample piece of code:

def main():
lambda x: 'ABC%s' % str(x)
for k in range(2): exec('print %s' % k)

main()

With the lambda line, I get this:
SyntaxError: unqualified exec is not allowed in function 'main'
it contains a nested function with free variables
Without the lambda, it's ok...

What's this ?

thanks
 
S

Scott David Daniels

Attila said:
Hi,
def main():
lambda x: 'ABC%s' % str(x)
for k in range(2): exec('print %s' % k)
OK, to no real effect, in main you define an unnamed function that
you can never reference. Pretty silly, but I'll bite.

Next you run run a loop with exec looking like you think it is a
function. In the loop, your "exec" statement does not control
(specify) its access to global and local variables. This could be
a problem if your function were different. The function above does
not do any up-referencing, but:

def main():
def inner():
return k + 1

for k in range(4):
exec 'k = 3 * k'
print k, inner()

What should this do?

If you think you know, how about replacing the exec line with:

exec raw_input('Tricky: ')

You can fix this by controlling what variables the exec can write:

exec 'k = 3 * k' in globals(), locals()

This is why locals() does not do write-back.

The rule below (which was high on the list when searching for exec),
tells the exact rules, the above stuff is just why.

http://www.python.org/doc/2.4/ref/dynamic-features.html

--Scott David Daniels
(e-mail address removed)
 
A

Attila Szabo

2005, Feb 25 -> Scott David Daniels wrote :
OK, to no real effect, in main you define an unnamed function that
you can never reference. Pretty silly, but I'll bite.

This code was simplified, the lambda was part of a map,
and the exec line is different too, I just wrote
this to picture the situation, but it's ok now...
At first I was surprised, but I read a bit and it's clear now...

Thanks
 
S

Scott David Daniels

Attila said:
2005, Feb 25 -> Scott David Daniels wrote :
This code was simplified, the lambda was part of a map, ...

I'm sorry, upon re-reading my reply, I see how it looks like a
snide comment. I apologize. I didn't mean to malign you, and
I did indeed appreciate that the code was obviously boiled down.
I just thought:
def named(x):
return 'ABC%s' % str(x)
provides a function name to talk about, exhibits the same problem,
and is "simpler".

--Scott David Daniels
(e-mail address removed)
 

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,983
Messages
2,570,187
Members
46,747
Latest member
jojoBizaroo

Latest Threads

Top