Back

Question:

What is closure?

How often asked: Rarely

Suggested by: ALittleMoron


Answer:

A closure is a nested function that preserves the context of the outer function even after it completes execution.

def make_multiplier(factor):
    def multiply(value):
        return value * factor
    return multiply


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

print(double(10))  # 20
print(triple(10))  # 30

The multiply function is a closure because:

  • it is defined within make_multiplier;
  • it uses the factor variable from the outer function;
  • it continues to have access to factor after make_multiplier completes.

Each call creates a separate environment. Therefore, a function created by make_multiplier(2) retains access to factor = 2, while one created by make_multiplier(3) retains access to factor = 3.

This feature in Python allows you to implement decorators, function factories, and stateful functions.


Interview answer explanation:

The interviewer is checking whether the candidate understands:

  • variable scopes;
  • nested functions;
  • lexical scoping;
  • variable lifetime;
  • functions as first-class objects;
  • how decorators and function factories work;
  • Python’s late-binding behavior.

The question also reveals whether the candidate can explain how a function can preserve state without using a global variable or a class.

The candidate should explain that a closure:

  • is a function;
  • refers to a variable from an enclosing scope;
  • retains access to that variable after the outer function has returned.

External resources: