Last Updated : 11 Dec, 2024
In Python, a closure is a powerful concept that allows a function to remember and access variables from its lexical scope, even when the function is executed outside that scope. Closures are closely related to nested functions and are commonly used in functional programming, event handling and callbacks.
A closure is created when a function (the inner function) is defined within another function (the outer function) and the inner function references variables from the outer function. Closures are useful when you need a function to retain state across multiple calls, without using global variables.
A Basic Example of Python ClosuresLet's break down a simple example to understand how closures work.
Python
def fun1(x):
# This is the outer function that takes an argument 'x'
def fun2(y):
# This is the inner function that takes an argument 'y'
return x + y # 'x' is captured from the outer function
return fun2 # Returning the inner function as a closure
# Create a closure by calling outer_function
closure = fun1(10)
# Now, we can use the closure, which "remembers" the value of 'x' as 10
print(closure(5))
Explanation:
Let's take a look at python closure in detail:
Example of Python closure: Python
def fun(a):
# Outer function that remembers the value of 'a'
def adder(b):
# Inner function that adds 'b' to 'a'
return a + b
return adder # Returns the closure
# Create a closure that adds 10 to any number
val = fun(10)
# Use the closure
print(val(5))
print(val(20))
In this example:
When a closure is created, Python internally stores a reference to the environment (variables in the enclosing scope) where the closure was defined. This allows the inner function to access those variables even after the outer function has completed.
In simple terms, a closure "captures" the values from its surrounding scope and retains them for later use. This is what allows closures to remember values from their environment.
Use of ClosuresRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4