#FutureSTEMLeaders - Wiingy's $2400 scholarship for School and College Students

Apply Now

Python

Python Closures

Written by Rahul Lath

Updated on: 07 Dec 2023

Python Tutorials

1Python Overview2Python Tutorial: A Comprehensive Guide for Beginners3Python Keywords and Identifiers4Download and Installation Guide for Python5Python Syntax (With Examples)6Python Comments7Python Variables (With Examples)8Taking Input in Python9Output in Python10File Handling in Python (Files I/O)11Python Operators (With Examples)12Ternary Operators in Python13Operator Overloading in Python14Division Operators in Python15Input from Console in Python16Output Formatting in Python17Any All in Python18Difference between Python Equality and Identity Operators19Python Membership and Identity Operators20Python Data Types21Python Dictionary22Control Flow in Python23Python Arrays24Looping Techniques in Python25Chaining Comparison Operators in Python26Python Functions27Python Strings28Python Numbers29Python Sets30Python For Loops31Python While Loops32Python Break Statement:33Python Continue Statement34Python pass Statement35Args and Kwargs in Python36Python Generators37Python Lambda38Global and Local Variables in Python39Global Keyword in Python40Python Closures41Python Decorators42Memoization using Decorators in Python43Constructors in Python44Encapsulation in Python45Inheritance in Python46Polymorphism in Python47Class Method vs Static Method in Python48Python Exception Handling49First Class Functions in Python50Python Classes And Objects51Errors and Exceptions in Python52Built-In Exceptions in Python53Append to file in Python54File Handling in Python55Destructors in Python56User-Defined Exceptions in Python57Class or Static Variable in Python58Python Tuples59Reading File in Python60Writing File in Python61Opening and Closing Files in Python62NZEC error in Python63Operator Function64Webscraper Python Beautifulsoup65Python Pyramid Patterns66Python Start Patterns67Web Crawler in Python68Build a Python Youtube Downloader69Currency Convertor in Python70Python Website Blocker
tutor Pic

What are Python Closures?

A closure in Python is a nested or inner function that has access to variables within the scope of the enclosing (outer) function. In order to create a “closure” that lasts even after the outer function has returned, it “closes” over the variables it requires from the outer function.

Higher-order functions, or functions that interact with other functions, can only be created with the help of closures. Closures make it possible to create functions that are customized on-the-fly, without requiring additional arguments or complicated logic, by allowing inner functions to access the state of the outer function.

Although they can be a little difficult for beginners to grasp, Python closures are a crucial concept to understand if you want to write complex Python code. Spending some time learning about closures and how they function is a good idea if you’re just getting started with Python programming.

Introduction to Closures in Python

Explanation of Closures:

In Python, a closure is a function that continues to have access to the variables in the scope of the enclosing function even after it has returned. When a nested function makes a reference to a value from the enclosing function, closures are created.

Understanding what, when & why to use closures!

If you want to write a function that can access state that endures across function calls, you should use closures. Iterators, generators, and other higher-order functions can be built using closures. They come in handy when you need to design a function that can be altered depending on an outside state.

Here’s an example:

def make_adder(x): def adder(y): return x + y return adder add5 = make_adder(5) add10 = make_adder(10) print(add5(3)) # Output: 8 print(add10(3)) # Output: 13

In this example, make_adder returns an inner function, adder, which “closes over” the value of x. When we call make_adder(5), we get back a function that adds 5 to its argument. When we call make_adder(10), we get back a function that adds 10 to its argument. We can then use these functions to add 5 or 10 to any number we like.

Scoping Rules and Nested Functions in Python

Overview of Functions:

A function in Python is a section of code that completes a particular task. Functions can accept arguments as inputs and return results in the form of return values. The def keyword is used to define functions, and parentheses are used to call them.

Understanding Inner and Outer Functions:

Functions defined inside of other functions are known as inner functions. The variables in the outer function’s scope are accessible to them, but not the other way around. Functions defined outside of any other function are known as outer functions.

Python Nested Function:

A function that is defined inside another function is referred to as nested. Like inner functions, nested functions have access to the variables in the outer function’s scope. However, nested functions cannot be accessed from outside the outer function and are only defined when the outer function is called.

Here’s an example:

def outer(x): def inner(y): return x + y return inner

Use closure attribute:

In Python, you can use the closure attribute to check if a function is a closure, and to inspect its free variables (the variables it “closes over”). Here’s an example:

/code start./ def make_counter():
    count = 0
    def counter():
        nonlocal count
        count += 1
        return count
    return counter

c = make_counter()
print(c()) # Output: 1
print(c()) # Output: 2

print(c.__closure__) # Output: (<cell at 0x7f9e3c3d6d10: int object at 0x7f9e3c4050c0>,)
print(c.__closure__[0].cell_contents) # Output: 2 

Written by

Rahul Lath

Reviewed by

Arpit Rankwar

Share article on

tutor Pic
tutor Pic