loop scope

David MacQuigg dmq at gain.com
Fri Mar 12 11:07:32 EST 2004


On Fri, 12 Mar 2004 14:06:38 GMT, Arthur <ajsiegel at optonline.com>
wrote:

>On Thu, 11 Mar 2004 17:54:56 -0700, David MacQuigg <dmq at gain.com>
>wrote:

>>Scopes are defined by the boundaries of functions, classes and
>>modules, not for loops.  This is essential, or you would have to
>>declare global variables inside most for loops.
>
>I am not following this argument.  The surprise, specifically,  is
>that I don't think of myself as having declared "t" as a variable.  it
>is don't magically, as a placeholder and for a very specific purpose.
>So I would expect it to go away outside of the " [ " and " ] " by
>equal and opposite magic.

The "declarations" are automatic, whenever you *use* a variable.  I
would *not* expect temporary variables in a loop to go away outside of
the loop.  It's just another variable in the current namespace.

I think I may have misunderstood your original question.  The title of
the thread is 'loop scope', but your question seems to be specifically
on the loop iteration variable 't'.  Just think of it as a normal
variable in the current local scope.

The one exception I can think of is what Terry Reedy mentioned - the
iteration variable in a list comprehension.  In some future
optimization, they may neglect to save that variable.  I hope they
don't do that (even though it really has no use).  I just like the
consistency we now have in treatment of all local variables.

-- Dave




More information about the Python-list mailing list