loop scope

Donn Cave donn at u.washington.edu
Mon Mar 15 13:26:41 EST 2004


In article <j4qb505fhlukq14p92ae961bfuhsurfo08 at 4ax.com>,
 David MacQuigg <dmq at gain.com> wrote:

> On Mon, 15 Mar 2004 14:43:20 GMT, Arthur <ajsiegel at optonline.com>
> wrote:

>> t=None #(or something) 
>>
>> required prior to a loop would  assure I am conscious of what I am
>> getting myself into.  Without it, it seems it isn't safe to assume the
>> user understands the full implications of simply complying with
>> required loop syntax.
>>
>> Wouldn't something like this make sense:
>>
>> With a loop iteration variable declared explicitly in the curent scope
>> and prior to the loop, it survives the loop.  Otherwise it is treated
>> as a placeholder within the loop, and goes out of scope at its
>> conclusion.
> 
> This is a little too tricky for my taste.  Often we need to 'break'
> from a loop, and subsequently use the value of 't'.  If we forget to
> "declare" 't' outside the loop, then we will have a situation where
> you get a run-time error if the loop ends without a break.

I didn't read anything there that proposed to make a distinction
between `ends with break' and `ends without break.'  That would
be a bad thing.

> What is the benefit of keeping 't' out of the surrounding local
> scope?"  This whole thread seems pointless unless there is a
> substantial benefit to changing the current behavior.

Well, the bottom line has to be whether it's easier to
read the code and understand what it does.  In a procedural
language like Python, variable scope is critical to that,
so it's important to get it right.  Unfortunately, I don't
know if there's a good answer.

Taking list comprehensions, because that's what the original
post took at least as an example and because that's the only
case that is new enough to half seriously consider changing -

   t = f(a/c)
   ... # and then later,
   sl = [t * t for t in range(3)]

In this case, I would argue that it's an error for t to escape
the expression scope _because_ it's used outside that scope -
actually I think that was where we came in.  My personal view
is that a list comprehension should have its own internal scope,
period, but is that what `intuition' would lead most Python
programmers to expect?  I don't know.

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list