strange SyntaxError

Scott David Daniels Scott.Daniels at Acm.Org
Fri Feb 25 10:02:13 EST 2005


Attila Szabo wrote:
> 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
Scott.Daniels at Acm.Org



More information about the Python-list mailing list