| A Basic Example of Python Closures | ||||||
|
a closure is a powerful concept that allows a function to remember and access variables
from its lexical scope closures are closely related to nested functions 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) 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 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)
# can use the closure, which "remembers" the value of 'x' as 10
print(closure(5))
|
||||||
| Example of Python closure | ||||||
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))
fun(10) creates a closure that remembers the value 10 and adds it to any number
passed to the closure
|
||||||
| How Closures Work Internally? | ||||||
|
when a closure is created, Python internally stores a reference to the environment
(variables in the enclosing scope) where the closure was defined allows the inner function to access those variables even after the outer function has completed a closure 'captures' the values from its surrounding scope and retains them for later use allows closures to remember values from their environment |
||||||
| Use of Closures | ||||||
|