Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 77 ยท Python Interview Questions

Python: Decorators, Closures and Context Managers

Answer Python interview questions on closures, decorator internals, functools.wraps, late binding in loops and the with statement, with runnable code.

Decorators, closures and context managers are the "do you really understand functions?" part of a Python interview. The questions sound advanced, but they all rest on two facts: functions are ordinary objects, and a function can remember the variables around it.

For the full tutorials see Decorators, Scope and Context Managers. This lesson is about short, correct answers and the traps interviewers like.

Three linked ideas

Closure A function that remembers its outer variables.
Decorator A function that takes a function and returns one.
Context manager Guarantees setup and cleanup around a block.

Decorators are built from closures. Context managers are built from two methods.

1 / 2

Closures

Q: What is a closure? A function together with the variables of the scope where it was defined. The inner function keeps using those variables after the outer function has returned. Python stores them in "cells", which you can inspect through __closure__.

Python A closure and its cell

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Follow-up: "Why nonlocal?" Assignment inside a function makes the name local. Without nonlocal, count += 1 would raise UnboundLocalError. nonlocal says "rebind the name in the nearest enclosing function".

Late binding

Q: What does this print?

Python
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])

A closure captures the variable, not its value at that moment. All three lambdas share one i, which is 2 after the loop. The fix is to bind the value at definition time with a default argument.

Python Late binding and the default-argument fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Decorators

Q: What is a decorator? A callable that takes a function and returns a replacement (usually a wrapper). The @name line is only shorthand:

Python
@timer
def work(): ...

# is exactly
work = timer(work)
Python A decorator built by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice the last two lines: the decorated function now reports the wrapper's name and no docstring. That leads to the most common follow-up.

functools.wraps

Q: Why use functools.wraps? It copies __name__, __doc__, __module__ and other metadata from the original to the wrapper, and sets __wrapped__ so tools can reach the original. Without it, debugging output, help() and introspection-based tools see the wrapper.

Python Fixing metadata with wraps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Decorators with arguments

Q: How do you write @repeat(3)? Add one more layer. repeat(3) runs first and returns the real decorator, which then receives the function. That is three nested functions: the factory, the decorator, and the wrapper.

Python A decorator factory and stacked decorators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Order of stacking: decorators apply bottom-up (the one nearest the function wraps first), so the top one is the outermost layer and runs first when you call the function. Above, log_calls prints before the repeated hello.

Other things worth knowing: decorators can be classes (implement __call__), they run once at definition time while the wrapper runs on every call, and functools.lru_cache is a standard-library decorator you should be able to explain.

Context managers

Q: What does with do? It calls __enter__ on the object, binds its return value after as, runs the block, and always calls __exit__, even if the block raised. If __exit__ returns a truthy value, the exception is suppressed. That makes it the right tool for files, locks, connections and temporary state.

Python Class-based context manager

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

contextlib.contextmanager

Q: Is there a shorter way? Yes. A generator with one yield becomes a context manager: code before yield is the enter, code after is the exit. Put the yield in try/finally so cleanup runs when the block raises.

Python A generator-based context manager

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common follow-up questions

  • Can a decorator be applied to a method? Yes. self simply arrives as the first item of *args.
  • Is a closure the same as a lambda? No. A lambda is a syntax for small anonymous functions. A closure is any function that uses variables from an enclosing scope.
  • Why does with beat try/finally? The cleanup is attached to the object, so it cannot be forgotten, and it is easy to reuse.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does @deco above def f() do?

    The decorator line is evaluated once when the function is defined and the name is rebound to whatever the decorator returns.
  2. 2. Why does [lambda: i for i in range(3)] give three functions that all return 2?

    Closures bind variables, not values. A default argument such as lambda i=i: i freezes the current value.
  3. 3. What does functools.wraps do?

    It also sets __wrapped__. It does not change behavior, only introspection data.
  4. 4. What happens if __exit__ returns True after the block raised an exception?

    A truthy return value from __exit__ tells Python the exception was handled.

Summary

  • A closure keeps the variables of its defining scope alive; nonlocal lets it rebind them.
  • Closures capture variables, not values: use default arguments or partial to freeze a loop value.
  • @deco means f = deco(f); stacked decorators apply bottom-up.
  • Always use functools.wraps in wrappers; a decorator with arguments needs three layers.
  • with guarantees __exit__ runs; contextlib.contextmanager builds one from a generator with try/finally.

Next: Python: OOP, MRO and the GIL.