Why aren't python nested functions called closures?

后端 未结 8 788
情歌与酒
情歌与酒 2020-11-22 05:37

I have seen and used nested functions in Python, and they match the definition of a closure. So why are they called nested functions instead of closures<

8条回答
  •  余生分开走
    2020-11-22 06:26

    Python 2 didn't have closures - it had workarounds that resembled closures.

    There are plenty of examples in answers already given - copying in variables to the inner function, modifying an object on the inner function, etc.

    In Python 3, support is more explicit - and succinct:

    def closure():
        count = 0
        def inner():
            nonlocal count
            count += 1
            print(count)
        return inner
    

    Usage:

    start = closure()
    start() # prints 1
    start() # prints 2
    start() # prints 3
    

    The nonlocal keyword binds the inner function to the outer variable explicitly mentioned, in effect enclosing it. Hence more explicitly a 'closure'.

提交回复
热议问题