Question39
Remaining:

What is a closure in Python?

Sample Answer

Show Answer by Default

A closure is a nested function that "remembers" variables from the enclosing function's scope, even after the enclosing function has finished its execution.

How it works:

def make_multiplier(factor):
    def multiply(number):
        return number * factor  # 'factor' is captured from the outer function
    return multiply

double = make_multiplier(2)
triple = make_multiplier(3)

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

Conditions for a closure:

  • There must be a nested function.
  • The nested function must refer to an environment variable from the enclosing function.
  • The enclosing function must return the nested function.

Practical applications:

# Counter
def make_counter(start=0):
    count = start
    def counter():
        nonlocal count
        count += 1
        return count
    return counter

c = make_counter()
print(c())  # 1
print(c())  # 2
print(c())  # 3

# Logger
def make_logger(prefix):
    def log(message):
        print(f"[{prefix}] {message}")
    return log

error_log = make_logger("ERROR")
error_log("File not found")  # [ERROR] File not found