Strange variable scope... is this right?

Alex Martelli aleaxit at yahoo.com
Sat Jan 13 12:28:45 EST 2001


<gradha at iname.com> wrote in message news:gcqp39.jkk.ln at 127.0.0.1...
    [snip]
> In another attempt to DTW (Dominate The World), I wrote an obfuscated loop
> just to see the scope behaviour of Python:
>
> f = ["row", "cow", "arrow"]
> for f in f:
>     print f
>     for f in range (len (f)):
>         print f
    [snip]
> AFAICS, python will create a different variable scope at both for's,
> hence the possibility to reuse the variable name f, since it means a
> different thing at each scope, being unavailable from outside it's scope.
>
> Is this a correct deduction? Is this related with the need to declare in

Not really.  When you do 'for f in f:', the expression after the 'in' is
evaluated and a reference to it is taken, then the variable between
'for' and 'in' is bound successively to the various items in said
(sequence) expression; there is no scope change, so, the first time
'f' is re-bound, it's not bound any more to the sequence.

Try this simple test:

f = ["row", "cow", "arrow"]
for f in f:
    print f
    if f=='cow': break
print f

and you'll see

row
cow
cow

i.e., 'f' stays bound to whatever it was last bound to in the loop,
after the loop itself is over.

In Python, 'scope' is defined by a module, function (including a
lambda), or class; a statement such as 'for' does not define another
scope.  What you're seeing, rather, is that, in an assignment or
equivalent (and 'for' is like a sequence of assignments, one after
the other), the right-hand side is evaluated (and a reference
bound to it) _before_ re-binding take place -- the same kind of
nicety that lets you write, e.g.:

    a, b = b, a

(both b and a on the RHS are evaluated first, the resulting
temporary unnamed tuple has references to the objects b
and a were bound for, then a and b are re-bound via the
references in the tuple -- all in all, a 'swap' takes place).


Alex







More information about the Python-list mailing list