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

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

1 day ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

3 weeks ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

3 weeks ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

4 weeks ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

4 weeks ago

Job Scheduler Implementation

Design a job scheduler that accepts a function f and an integer n. The scheduler…

4 weeks ago