Scope in 2.2.1

Tim Peters tim.one at comcast.net
Sat May 11 13:48:00 EDT 2002


[David LeBlanc]
> ...
> I have grown accustomed by long use to the way that C, C++ and Pascal
> (and asm for that matter!) become aware of declarations.

Since Python doesn't have any declarations, it would be hard for Python to
act the same way <wink>.  It acts "as if" there were a local declaration at
the top of a block for every variable that appears in a binding context
within the block.

> ...
> Python seems to have an implicit per block pre-pass that gets all the
> bindings before statements are parsed.  Is this the correct idea?

Pretty much.  I think the Ref Man is quite clear about this:

    Whether a name is local or global in a code block is determined by
    static inspection of the source text for the code block:  in the
    absence of global statements, a name that is bound anywhere in the
    code block is local in the entire code block; all other names are
    considered global.

With the introduction of nested scopes, it would be more accurate to change
the first and last instances of "global" to "non-local".

[Alex]
>> def f(x):
>>     if x==23: x=45
>>     print x
>>
>> the x in the print may reference either the same binding as given by
>> f's caller, or the binding to 45.  It IS certainly a reference to the
>> *local variable* named x, but what binding of that local variable
>> applies, it's anybody's guess.  "scoping" might be a useful neologism
>> here.

> gaaaaa! this is mad! How can you write a sane program in this sort of
> environment?!?

You're misreading Alex here.  The name 'x' is local in f, period.  But
exactly as in C or Pascal or whatever too, at the time you get to the print
statement, you can't guess who most recently *assigned* a value to x.  If
the caller did f(100), then the caller supplied the 100 that gets printed;
if the caller did f(23), then the 45 that gets printed was supplied by the
"x=45" in f.  Alex's point here is more trivial than profound.  x is in f's
local namespace regardless, but since x is an argument to f, you can't in
general guess whether its final binding came from binding x to the value
passed from the caller, or from the conditional "x=45".  That much is true
in virtually all languages with named arguments.






More information about the Python-list mailing list