What is a Python closure?
Elshad Karimov
Founder of AppMillers | ERP Expert | Teaching more than 200k people How to Code.
A Python closure is a way of keeping and carrying around a set of variables from the environment in which a function was created. It’s like packing a suitcase with everything you need for a trip, so you have your essentials with you even when you’re far from home. Let’s make this concept easy and fun to understand!
Imagine you have a magic box ?? that can remember and store certain things (variables) you put into it. Now, suppose you also have a special toy robot ?? (a function) that can do some tasks for you, like drawing a picture or solving a math problem. But, this robot needs some specific instructions or tools (variables) to do its job correctly.
Here’s the catch: you want your robot to be able to do its job anywhere, not just at home where it has access to all its tools. So, what do you do? You pack a smaller box with the specific tools (variables) it needs and attach this box to your robot. Now, wherever the robot goes, it carries its little box of tools with it, allowing it to do its job anywhere. This smaller box attached to the robot is like a closure in Python.
In Python terms, a closure is created when a nested function (the robot) remembers the values from its enclosing scope (the magic box) even after the outer function has finished executing. This means the nested function can access those captured variables even when it’s called outside of its original context.
领英推荐
Here’s a simple example to illustrate closures in Python:
def outer_function(message):
# This is the enclosing scope
def inner_function():
# This is the nested function that forms a closure
print(message)
return inner_function
# Create a closure
my_closure = outer_function("Hello, World!")
# Even though outer_function has finished executing,
# my_closure remembers the 'message' variable
my_closure() # Outputs: Hello, World!
In this example, inner_function is a closure that remembers the value of message from the enclosing outer_function. Even after we exit outer_function, my_closure (which is inner_function) still has access to message.
Closures are useful for creating decorators, maintaining state in a functional way, and writing more concise and readable code.