[Python-Dev] violently deprecating exec without in (was: nested scopes. global: have I got it right?)
Jeremy Hylton
jeremy@alum.mit.edu
Thu, 1 Mar 2001 20:12:37 -0500 (EST)
>>>>> "GvR" == Guido van Rossum <guido@digicool.com> writes:
>> > SP> # top-level
>> > SP> def g():
>> > SP> exec "x=3" return x
GvR> [me]
>> Unfortunately this used to work, using a gross hack: when an exec
>> (or import *) was present inside a function, the namespace
>> semantics *for that function* was changed to the pre-0.9.1
>> semantics, where all names are looked up *at run time* first in
>> the locals then in the globals and then in the builtins.
>>
>> I don't know how common this is -- it's pretty fragile. If
>> there's a great clamor, we can put this behavior back after b1 is
>> released.
GvR> I spoke too soon. It just works in the latest 2.1b1. Or am I
GvR> missing something?
The nested scopes rules don't kick in until you've got one function
nested in another. The top-level namespace is treated differently
that other function namespaces. If a function is defined at the
top-level then all its free variables are globals. As a result, the
old rules still apply.
Since class scopes are ignored for nesting, methods defined in
top-level classes are handled the same way.
I'm not completely sure this makes sense, although it limits code
breakage; most functions are defined at the top-level or in classes!
I think it is fairly clear, though.
Jeremy