Open In App

Python Closures

Last Updated : 09 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Before seeing what a closure is, we have to first understand what nested functions and non-local variables are. 

Nested functions in Python

A function that is defined inside another function is known as a nested function. Nested functions are able to access variables of the enclosing scope. 

In Python, these non-local variables can be accessed only within their scope and not outside their scope. This can be illustrated by the following example: 

Python3




# Python program to illustrate
# nested functions
def outerFunction(text):
 
    def innerFunction():
        print(text)
 
    innerFunction()
 
 
if __name__ == '__main__':
    outerFunction('Hey!')


Output:

Hey!

As we can see innerFunction() can easily be accessed inside the outerFunction body but not outside of its body. Hence, here, innerFunction() is treated as a nested Function that uses text as a non-local variable.

What are Python Closures

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

  • It is a record that stores a function together with an environment: a mapping associating each free variable of the function (variables that are used locally but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.
  • A closure—unlike a plain function—allows the function to access those captured variables through the closure’s copies of their values or references, even when the function is invoked outside their scope.

Python3




# Python program to illustrate
# closures
def outerFunction(text):
 
    def innerFunction():
        print(text)
 
    # Note we are returning function
    # WITHOUT parenthesis
    return innerFunction 
 
if __name__ == '__main__':
    myFunction = outerFunction('Hey!')
    myFunction()


Output:

omkarpathak@omkarpathak-Inspiron-3542:
~/Documents/Python-Programs/$ python Closures.py 
Hey!

As observed from the above code, closures in Python help to invoke functions outside their scope. The function innerFunction has its scope only inside the outerFunction. But with the use of Python closures, we can easily extend its scope to invoke a function outside its scope.

Python3




# Python program to illustrate
# closures
import logging
logging.basicConfig(filename='example.log',
                    level=logging.INFO)
 
def logger(func):
    def log_func(*args):
        logging.info(
            'Running "{}" with arguments {}'.format(func.__name__,
                                                    args))
        print(func(*args))
         
    # Necessary for closure to
    # work (returning WITHOUT parenthesis)
    return log_func            
 
def add(x, y):
    return x+y
 
def sub(x, y):
    return x-y
 
add_logger = logger(add)
sub_logger = logger(sub)
 
add_logger(3, 3)
add_logger(4, 5)
 
sub_logger(10, 5)
sub_logger(20, 10)


Output:

omkarpathak@omkarpathak-Inspiron-3542:
~/Documents/Python-Programs/$ python MoreOnClosures.py 
Running "add" with arguments6
9
5
10

~/Documents/Python-Programs/$ cat example.log
INFO:root:Running "add" with arguments (3, 3)
INFO:root:Running "add" with arguments (4, 5)
INFO:root:Running "sub" with arguments (10, 5)
INFO:root:Running "sub" with arguments (20, 10)

An important thing to note here, is that we can get to know what variables are stored inside a Closure with the help of the __closure__ attribute that makes use of Cell Objects to store the variables of the Outer Function and because of this, the closure can use these variables even when the Outer Function is terminated.

When and Why to Use Closures

  1. As Python closures are used as callback functions, they provide some sort of data hiding. This helps us to reduce the use of global variables.
  2. When we have few functions in our code, closures in Python prove to be an efficient way. But if we need to have many functions, then go for class (OOP).
  3. We may have variables in the global scope that are not used by many functions at times. Instead of defining variables in global scope, consider using a closure. They can be defined in the outer function and used in the inner function. Python Closures are also useful for avoiding the use of a global scope.
  4. A class in the Python programming language always has the __init__ method. If you only have one extra method, an elegant solution would be to use a closure rather than a class. Because this improves code readability and even reduces the programmer’s workload. Closures in Python can thus be used to avoid the needless use of a class.


Previous Article
Next Article

Similar Reads

Closures And Decorators In Python
Closures and decorators are powerful features in Python that allow for more advanced and flexible code patterns. Understanding these concepts can greatly enhance your ability to write clean, efficient, and reusable code. Why Python decorators rather than closures?Python decorators are preferred over closures for their readability, reusability, and
3 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Python | Merge Python key values to list
Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let's discuss certain ways in which this problem can be solved.
4 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python, two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now
5 min read
Python | Visualizing O(n) using Python
Introduction Algorithm complexity can be a difficult concept to grasp, even presented with compelling mathematical arguments. This article presents a tiny Python program that shows the relative complexity of several typical functions. It can be easily adapted to other functions. Complexity. Why it matters? Computational complexity is a venerable su
3 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
Article Tags :
Practice Tags :