A closure is a function object that remembers values in enclosing scopes even if they are not present in memory. Here’s an example to demonstrate how closures work in Python.
def power_of(exponent):
"""Return a function that raises a number to the given exponent."""
def power(base):
return base ** exponent
return power
# Create functions for squaring and cubing numbers
square = power_of(2)
cube = power_of(3)
print(f"5 squared is {square(5)}")
print(f"3 cubed is {cube(3)}")
exponent
as an argument.power_of
, a nested function power
is defined, which takes a base
as an argument and returns base
raised to the exponent
.power
function is returned by power_of
, creating a closure that captures the exponent
value.square
is created by calling power_of(2)
, resulting in a function that squares a number.cube
is created by calling power_of(3)
, resulting in a function that cubes a number.square(5)
computes 52=255^2 = 2552=25.cube(3)
computes 33=273^3 = 2733=27.When you run the above code, you will get the following output:
5 squared is 25
3 cubed is 27