Python Mastery โ€“ From Basics to Brilliance / Functions

Closure in Python

๐Ÿ”’ Closures

A closure is a function that remembers and can access variables from its enclosing function, even after the enclosing function has finished executing.


๐Ÿ”น Basic Example

def outer():
    message = "Hello"

    def inner():
        print(message)

    return inner

greet = outer()
greet() #Hello

How it works:

The inner() function is a closure because it remembers the variable message from outer().


๐Ÿ”น Closure with a Parameter

def multiplier(x):

    def multiply(y):
        return x * y

    return multiply

double = multiplier(2)
triple = multiplier(3)

print(double(5)) #10
print(triple(5)) #15

Here:

double โ†’ remembers x = 2
triple โ†’ remembers x = 3

Even though multiplier() has finished executing, the returned functions remember their respective values of x.


๐Ÿ”’ Example Counter

A closure is an inner function that remembers variables from its outer function even after the outer function finishes.

def make_counter():
    count = 0

    def counter():
        nonlocal count
        count += 1
        return count

    return counter

๐Ÿ”„ How it works

counter = make_counter()
  • count starts at 0

  • make_counter() returns counter

  • counter() remembers count

print(counter())  # 1
print(counter())  # 2
print(counter())  # 3

count keeps its value between calls because of the closure.

๐Ÿ”‘ nonlocal

nonlocal count

means:

"Use and modify the count from the outer function."

Closure = Inner function + remembered outer variable ๐Ÿ”’


โญ Why Use Closures?

Closures are useful for:

  • ๐Ÿ” Data hiding

  • โš™๏ธ Creating customized functions

  • ๐ŸŽจ Decorators

  • ๐Ÿงฉ Maintaining state between function calls

โญ Remember

Closure = A function + the variables it remembers from its enclosing scope.

def outer(x):
    def inner():
        return x
    return inner

Here, inner() remembers x even after outer() has finished.