Skip to content Skip to sidebar Skip to footer

Ways To Avoid That For-loop Variables Cut Into Python's Global Namespace

I am wondering if there is a way to avoid that for-loop variables cut into Python's global namespace? The only solution I could come up with so far would be using closures, such as

Solution 1:

for loops don't have their own scope in Python; there is only surrounding scope. So any variable defined in the for expression will persist in that scope. They're only being added into the global scope because you're running your code outside of a function. If you add it into a function, you'll see it doesn't "leak":

defloop():
    for j inrange(5):
        pass>>> loop()
>>> 'j'inglobals()
False

In Python 2.x, list comprehensions had the exact same behaviour: they would add the iterated variable into the local scope, as they were fundamentally syntactic sugar for the for construct. As this seemed to continually surprise people, it was changed for Python 3.x so that the variables aren't added to the local scope.

Also note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a list() constructor, and in particular the loop control variables are no longer leaked into the surrounding scope.

What's New In Python 3.0

The scope behaviour of for loops is useful for patterns like the following:

# find line number in file with matching textfor i, line inenumerate(some_file):
    if'some text'in line:
        breakprint('First match found at line {}.'.format(i))

Post a Comment for "Ways To Avoid That For-loop Variables Cut Into Python's Global Namespace"