Categories: python

Python Closures

Before we can understand what a closure is, we must first understand nested functions and non-local variables.

Nested functions in Python:

In Python, a function can be defined inside another function, creating a nested function. A nested function has access to the variables and parameters of the containing function, known as the enclosing function. This allows for creating more complex and reusable code.

Here is an example of a nested function in Python:

def outer_function(x):
    def inner_function(y):
        return x + y
    return inner_function

result = outer_function(10)(5)
print(result)  # prints 15

In this example, the outer function outer_function(x) takes an argument x and returns the inner function inner_function(y). The inner function takes an argument y and returns the sum of x and y.

Python Closures:

In Python, a closure is a nested function that can remember and access variables from its containing function, even after the containing function has finished executing. Closures are often used in situations where you want to create a function with some pre-configured behavior.

Here is an example of a closure in Python:

def outer_function(x):
    def inner_function():
        print(x)
    return inner_function

closure = outer_function(10)
closure()  # prints 10

In this example, the outer function outer_function(x) takes an argument x and returns the inner function inner_function(). The inner function has access to the variable x from the outer function, even though the outer function has finished executing.

When we call outer_function(10), it returns inner_function with the value of x that was passed to it, the returned function is assigned to the variable closure, later when we call closure() it will print 10.

Closures can also be used to create decorators, which are special kinds of functions that modify the behavior of other functions.

def my_decorator(func):
    def wrapper():
        print("Before calling the function")
        func()
        print("After calling the function")
    return wrapper

@my_decorator
def my_function():
    print("Inside the function")

my_function()

In this example, the my_decorator is a closure that takes a function as an argument and returns a new function that wraps the original function with additional behavior. The @my_decorator notation is a shorthand for calling my_decorator(my_function) and assigning the result back to my_function.

When we call my_function(), it will first execute the wrapper function, which will print “Before calling the function”, call the original function, then print “After calling the function”.

Closures are a powerful feature of Python, they allow you to bundle some data (the closed-over variables) together with the code that manipulates them (the inner function), creating a new kind of callable.

Closures: Important Things to Remember

The following are some useful points that are also required conditions for implementing closures in Python:

  • There should be nested functions, or functions within functions.
  • The inner function must refer to a non-local variable or the outer function’s local variable.
  • The inner function must be returned by the outer function.

Note: also read about Generators in Python

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago