Python Closures



The closure is a function object that remembers the values of closed space even if it is not present in memory.

A nested function is a function that is defined within another function. It is important to note that nested functions can access closed space variables. Yet, at least in Python, they are just for reading. However, anyone can use the keyword "nonlocal" to specify these variables.


Example 1

def myFunc(name):
    name = name

    def innerFunc():
        print(name)

    innerFunc()

if __name__ == '__main__':
    myFunc("Denny")

Output

Denny

Example 2

def myFunc(name):
    name = name

    def innerFunc():
        print(name)

    return innerFunc

if __name__ == '__main__':
    nameFunc = myFunc("Denny")
    nameFunc()

Output

Denny