Python Intermediate: What is the concept of Closure in Python

Home /

Table of Contents

Python Closures

The closure is a function object that has access to variables in its enclosing lexical scope, even when the function is called outside that scope. A closure is a nested function that is returned by a function or passed as an argument to another function. The returned function retains access to variables defined in the enclosing function’s scope, even after the enclosing function has finished execution.

Closures are used for a variety of purposes, such as creating higher-order functions, which are functions that take other functions as arguments or return functions as values. They are also used to create function factories, which are functions that generate other functions with specific properties. Closures can also be used to maintain a state in a functional programming paradigm. You also can check JavaScript Closure.

One important thing to note is that closures are created when a function is defined, not when it is executed. This means that each closure has a unique set of values for its enclosed variables, even if the function is called multiple times.

Closures can be a powerful tool in Python programming, but they can also be a source of confusion if not used correctly. It’s important to understand how closures work and when to use them to ensure that your code is efficient, readable, and maintainable.

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

Python nested functions

A nested function is one that is defined within another function. Nested functions have access to variables in the enclosing scope. These non-local variables in Python can only be accessed within their scope and not outside of it. The following example demonstrates this:

Example:

def external(text_value):
   text_value = text_value
 
   def internal():
       print(text_value)
 
   internal()
 
if __name__ == '__main__':
   external('Enablegeek is awesome!')
 

Output:

Enablegeek is awesome!

As we can see, Internal() is easily accessible within the External() body but not outside of it. As a result, External() is viewed as a nested Function that employs text as a non-local variable.

Closures Overview

Closures are function objects that remember values in enclosing scopes even if they are not in memory.

It is a record that records a function and its environment: a mapping that associates each free variable of the function (variables used locally but declared in an enclosing scope) with the value or reference to which the name was bound when the closure was formed. Unlike a regular function, a closure allows the function to access those captured variables via the closure’s copies of their values or references even when the function is run outside its scope.

Example:

def external(closer_text):
   closer_text = closer_text
 
   def internal():
       print(closer_text)
 
   return internal
 
if __name__ == '__main__':
   closure = external('Enablegeek is awesome!')
   closure()
 

Output:

Enablegeek is awesome!

Closures provide some data concealing since they are utilized as callback functions. This allows us to use fewer global variables.

Closures are an effective approach to writing code when we just have a few functions. However, if we require a large number of functions, we should use a class (OOP).

Closures are an important feature in Python as they allow for greater flexibility and control in the handling of functions and variables. They are often used in situations where a particular function needs to access and modify variables that are not in its local scope.

One of the primary benefits of closures is that they can be used to create specialized functions that are tailored to specific use cases. For example, a closure can be used to create a function that takes a single argument and returns a new function that adds that argument to any number passed to it. This can be useful for creating reusable code that can be applied to different situations.

Closures also help to improve code readability and maintainability by reducing the need for global variables and other complex data structures. By encapsulating functions and data within a closure, it becomes easier to understand and modify the code.

Overall, closures are an important tool in the Python programmer’s toolkit, allowing for greater flexibility and control in the creation and manipulation of functions and data.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.

Other Recommended Article