[Python-Dev] variable name resolution in exec is incorrect

Reid Kleckner rnk at mit.edu
Thu May 27 22:05:26 CEST 2010


On Thu, May 27, 2010 at 11:42 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> However, attaining the (sensible) behaviour Colin is requesting when such
> top level variable references exist would actually be somewhat tricky.
> Considering Guido's suggestion to treat two argument exec like a function
> rather than a class and generate a closure with full lexical scoping a
> little further, I don't believe this could be done in exec itself without
> breaking code that expects the current behaviour.

Just to give a concrete example, here is code that would break if exec
were to execute code in a function scope instead of a class scope:

exec """
def len(xs):
    return -1
def foo():
    return len([])
print foo()
""" in globals(), {}

Currently, the call to 'len' inside 'foo' skips the outer scope
(because it's a class scope) and goes straight to globals and
builtins.  If it were switched to a local scope, a cell would be
created for the broken definition of 'len', and the call would resolve
to it.

Honestly, to me, the fact that the above code ever worked (ie prints
"0", not "-1") seems like a bug, so I wouldn't worry about backwards
compatibility.

Reid


More information about the Python-Dev mailing list