Strange variable scope... is this right?

Emile van Sebille emile at fenx.com
Wed Jan 17 19:52:17 EST 2001


Ok.

Now, for the benefit of those of us (or is it just me ;-)
who thought we were getting the hang of code blocks,
execution frames and namespaces, it would appear that a for
loop pushes references to pop before entering the loop, ala:

r = range(5)
for i in r:
    if i == 1: del r
    print i,            #--> 0 1 2 3 4

However, when del-ing a slice, the presumed pushed
references are changed:

r = range(5)
for i in r:
    if i == 1: del r[2:4]
    print i,            #--> 0 1 4

Therefore, it must be simply a reference to the source
object (r) that gets pushed.

Assuming that's correct then, is this piece of code with
annotations the way that it's working?

f = ["row", "cow", "arrow"]
# create three element list object and bind to 'f'
for f in f:
    # save reference to 'f' to iterate over,
    # re-binding 'f' to each in turn
    for f in range (len (f)):
        # save reference to newly created range object of
len (f)
        # re-binding 'f' to each in turn

It feels like this is less an issue with namespaces and more
an issue of how the for loop works.

Am-I-getting-closer-ly y'rs,

--

Emile van Sebille
emile at fenx.com
-------------------


"Aahz Maruch" <aahz at panix.com> wrote in message
news:9456dr$a7h$1 at panix2.panix.com...
> In article <gcqp39.jkk.ln at 127.0.0.1>,  <gradha at iname.com>
wrote:
> >
> >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
>
> Since nobody else has suggested this, try a simple test:
>
> f = ["row", "cow", "arrow"]
> for f in f:
> for f in range (len (f)):
> print f
> print f
> --
>                       --- Aahz (Copyright 2001 by
aahz at pobox.com)
>
> Androgynous poly kinky vanilla queer het    <*>
http://www.rahul.net/aahz/
> Hugs and backrubs -- I break Rule 6
>
> A house is a machine to keep your cat dry.  --Aahz





More information about the Python-list mailing list