Nested Scopes unintended behaviour ?
Terry Reedy
tjreedy at udel.edu
Thu Mar 18 17:13:18 EDT 2010
On 3/18/2010 6:21 AM, Michael Sparks wrote:
> After hearing it's expected behaviour in 2.6 it's clear that assigning
> a name to a value declares the variable to be local,
unless there is a global/nonlocal declaration
and that unlike
> much of python (but like yield) this appears based on static analysis
> of the function declaration, rather than dynamic.
The language definition requires two passes after parsing.
One collects names and determines their scope (and looks for yield). The
second generates code.
This allows the local namespace to be implemented as an array rather
than a dict, so that local name lookup is an array index operation
rather than a dict lookup operation. This is somewhat made visible by
the dis module
>>> from dis import dis
>>> a = 1
>>> def f():
b = 2
return a,b
>>> dis(f)
2 0 LOAD_CONST 1 (2)
3 STORE_FAST 0 (b)
3 6 LOAD_GLOBAL 0 (a)
9 LOAD_FAST 0 (b)
12 BUILD_TUPLE 2
15 RETURN_VALUE
STORE/LOAD_FAST means store/load_local. Constants (2 in this case) are
stored in the same array. There is apparently a separate array of global
names, as opposed to local values.
Terry Jan Reedy
More information about the Python-list
mailing list