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.

Closures Example

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)}")


  1. power_of Function:
    • This is a higher-order function that takes an exponent as an argument.
    • Inside power_of, a nested function power is defined, which takes a base as an argument and returns base raised to the exponent.
    • The power function is returned by power_of, creating a closure that captures the exponent value.
  2. Creating Closure Functions:
    • 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.
  3. Using the Closure Functions:
    • 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