Why nested functions can access variables from outer functions, but are not allowed to modify them [duplicate] Why nested functions can access variables from outer functions, but are not allowed to modify them [duplicate] python python

Why nested functions can access variables from outer functions, but are not allowed to modify them [duplicate]


In Python 3.x this is possible:

def f1():        x = 5        def f2():                nonlocal x                x+=1        return f2

The problem and a solution to it, for Python 2.x as well, are given in this post. Additionally, please read PEP 3104 for more information on this subject.


def f1():    x = { 'value': 5 }    def f2():        x['value'] += 1

Workaround is to use a mutable object and update members of that object. Name binding is tricky in Python, sometimes.