Home  >  Article  >  Backend Development  >  How can Nonlocal Variables be Accessed in Closures in Python 2.x?

How can Nonlocal Variables be Accessed in Closures in Python 2.x?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-22 08:38:30402browse

How can Nonlocal Variables be Accessed in Closures in Python 2.x?

Accessing Nonlocal Variables in Closures in Python 2.x

In Python 2.x, the nonlocal keyword, used for accessing and rebinding nonlocal variables in closures, is not available. However, inner functions can still read nonlocal variables, albeit with limitations.

To bypass the lack of a nonlocal keyword, one can utilize a dictionary to store data. Inner functions can then access and modify the objects stored in the dictionary, even though they cannot directly rebind the nonlocal variables themselves.

Consider the following example:

def outer():
    d = {'y' : 0}
    def inner():
        d['y'] += 1
        return d['y']
    return inner

f = outer()
print(f(), f(), f()) #prints 1 2 3

Here, the outer function creates a dictionary 'd' and assigns to it a value for 'y'. The inner function can access and increment 'y' stored in the dictionary. The result is that each invocation of 'f()' returns an incremented value, demonstrating that inner functions can modify nonlocal objects indirectly.

The above is the detailed content of How can Nonlocal Variables be Accessed in Closures in Python 2.x?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn