Python Closures

A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory.

First of all understand, a Nested Function is a function that defined inside another function. It’s very important to note that the nested functions can access the variables of the enclosing scope. However, at least in python, they are only read only. However, one can use the “nonlocal” keyword explicitly with these variables in order to modify them.

Example of Nested Function

def outer(text):
    text = text

    def inner():
        print(text)
        
    inner()

if __name__ == '__main__':
    outer('Hello')
Tutorials Class - Output Window

Hello

Example of Python Closure

In this example we can see that closures help to invoke functions outside their scope.

inner() function has its scope only inside the outer() function but we can extend the scope of inner() function with help of closure to invoke a function outside its scope.

def outer(text):
    text = text
    def inner():
        print(text)

    return inner  # returning function without parenthesis

if __name__ == '__main__':
    myFunc = outer('Hello')
    myFunc()
Tutorials Class - Output Window

Hello


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.