[Tutor] inconsistent destruction
Steven D'Aprano
steve at pearwood.info
Thu Aug 8 08:34:19 CEST 2013
On Wed, Aug 07, 2013 at 08:54:26PM -0700, Jim Mooney wrote:
> This bugs me for some reason. The final variable is saved in a for
> loop but not in a list comprehension. It just seems to me they should
> both be destroyed to avoid confusion.
The variable in a for-loop is deemed to be in the same scope as the rest
of the function, the same as any other local variable. This is often
very useful:
for item in objects:
if condition(item):
break
print(item)
If for-loops introduced their own scope, as they do in a few other
languages, you would need to do something like this:
found = None
for item in objects:
if condition(item):
found = item
break
print(found)
On the other hand, list comprehensions (since Python 3) and generator
expressions (always) are deemed to exist in their own scope. That makes
conceptual sense, since a generator expression is its own chunk of
executable code, like a function, and in fact are implemented much the
same way that functions are implemented internally. List comps look the
same, and since Python 3 are now treated the same. That way you can use
a list comp or generator expression without worrying that its loop
variable will clobber an existing local variable of the same name.
[...]
> Is there a form of for loop that would destroy the loop variable? I
> could always do del cnt right after the for, but that seems
> artificial.
Why do you care? The typical function is chock full of local variables
that are used a few times, then hang around doing nothing until the
function exits. This doesn't cause any problems in practice.
--
Steven
More information about the Tutor
mailing list