Python Closures: Common Use Cases and Examples
by:
blow post content copied from Real Python
click here to view original post
In Python, a closure is typically a function defined inside another function. This inner function grabs the objects defined in its enclosing scope and associates them with the inner function object itself. The resulting combination is called a closure.
Closures are a common feature in functional programming languages. In Python, closures can be pretty useful because they allow you to create function-based decorators, which are powerful tools.
In this tutorial, you’ll:
- Learn what closures are and how they work in Python
- Get to know common use cases of closures
- Explore alternatives to closures
To get the most out of this tutorial, you should be familiar with several Python topics, including functions, inner functions, decorators, classes, and callable instances.
Get Your Code: Click here to download the free sample code that shows you how to use closures in Python.
Take the Quiz: Test your knowledge with our interactive “Python Closures: Common Use Cases and Examples” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
Python Closures: Common Use Cases and ExamplesIn this quiz, you'll test your understanding of Python closures. Closures are a common feature in functional programming languages and are particularly popular in Python because they allow you to create function-based decorators.
Getting to Know Closures in Python
A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope. When the enclosing function returns the inner function, then you get a function object with an extended scope.
In other words, closures are functions that capture the objects defined in their enclosing scope, allowing you to use them in their body. This feature allows you to use closures when you need to retain state information between consecutive calls.
Closures are common in programming languages that are focused on functional programming, and Python supports closures as part of its wide variety of features.
In Python, a closure is a function that you define in and return from another function. This inner function can retain the objects defined in the non-local scope right before the inner function’s definition.
To better understand closures in Python, you’ll first look at inner functions because closures are also inner functions.
Inner Functions
In Python, an inner function is a function that you define inside another function. This type of function can access and update names in their enclosing function, which is the non-local scope.
Here’s a quick example:
>>> def outer_func():
... name = "Pythonista"
... def inner_func():
... print(f"Hello, {name}!")
... inner_func()
...
>>> outer_func()
Hello, Pythonista!
>>> greeter = outer_func()
>>> print(greeter)
None
In this example, you define outer_func()
at the module level or global scope. Inside this function, you define the name
local variable. Then, you define another function called inner_func()
. Because this second function lives in the body of outer_func()
, it’s an inner or nested function. Finally, you call the inner function, which uses the name
variable defined in the enclosing function.
When you call outer_func()
, inner_func()
interpolates name
into the greeting string and prints the result to your screen.
Note: To learn more about inner functions, check out the Python Inner Functions: What Are They Good For? tutorial.
In the above example, you defined an inner function that can use the names in the enclosing scope. However, when you call the outer function, you don’t get a reference to the inner function. The inner function and the local names won’t be available outside the outer function.
In the following section, you’ll learn how to turn an inner function into a closure, which makes the inner function and the retained variables available to you.
Function Closures
All closures are inner functions, but not all inner functions are closures. To turn an inner function into a closure, you must return the inner function object from the outer function. This may sound like a tongue twister, but here’s how you can make outer_func()
return a closure object:
>>> def outer_func():
... name = "Pythonista"
... def inner_func():
... print(f"Hello, {name}!")
... return inner_func
...
>>> outer_func()
<function outer_func.<locals>.inner_func at 0x1066d16c0>
>>> greeter = outer_func()
>>> greeter()
Hello, Pythonista!
Read the full article at https://realpython.com/python-closure/ »
[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]
October 30, 2024 at 07:30PM
Click here for more details...
=============================
The original post is available in Real Python by
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================
Post a Comment