Python Decorators Interview Questions
Last updated 2026-11-19
Decorators are a favourite intermediate Python topic because they test closures, first-class functions and the call mechanism all at once. A typical round starts with what a decorator is, moves to writing a timing or logging decorator, and ends with a puzzle about stacking order or arguments.
The questions here build from the basic wrapper pattern to decorators with parameters, class-based decorators and the standard-library ones you are expected to know, such as functools.wraps, lru_cache and property.
| Level | 1 to 4 years |
|---|---|
| Focus | Closures, wrappers, functools |
| Version | Python 3.9 and later |
The one idea to remember
A decorator is just a callable that takes a function and returns a function (or any callable). The syntax @dec above def f is shorthand for f = dec(f), executed once when the def statement runs.
Everything else, such as arguments and stacking, follows from that line.
Related reading
Decorators depend on closures, covered in the Python interview questions page and on first-class functions in lambda and functional programming. Both sit within the broader Python interview preparation guide.
Python Decorators Interview Questions: questions with worked answers
1 What is a decorator in Python?
easyA decorator is a function that takes another function, adds behaviour around it and returns the result, without modifying the original source. It relies on functions being first-class objects and on closures. The line @log placed above def f is exactly f = log(f). Typical uses are logging, timing, authentication checks, caching and retry logic.
2 Write a simple timing decorator.
easyDefine an outer function that accepts the target, an inner wrapper that accepts any arguments, calls the target and returns its result, and return the wrapper. Forgetting to return the result, or to accept *args and **kwargs, is the most common mistake. The decorator runs once at definition time, the wrapper runs on each call.
pythonimport time def timed(fn): def wrapper(*args, **kwargs): t = time.perf_counter() result = fn(*args, **kwargs) print(f"{fn.__name__} took {time.perf_counter() - t:.4f}s") return result return wrapper @timed def work(n): return sum(range(n)) work(1_000_000)3 Why use functools.wraps?
mediumWithout it the wrapper replaces the original's metadata, so f.__name__ becomes 'wrapper' and the docstring is lost, which breaks debugging, help() and introspection tools. functools.wraps(fn) copies __name__, __doc__, __module__ and others, and sets __wrapped__ pointing at the original.
pythonfrom functools import wraps def deco(fn): @wraps(fn) def wrapper(*a, **k): return fn(*a, **k) return wrapper @deco def add(a, b): "Add two numbers." return a + b print(add.__name__, add.__doc__) # add Add two numbers.4 How do you write a decorator that takes arguments?
mediumAdd one more level: an outer function takes the arguments and returns the actual decorator. So @repeat(3) first calls repeat(3), and the returned function then decorates the target. That makes three nested layers: arguments, function, call.
pythonfrom functools import wraps def repeat(times): def deco(fn): @wraps(fn) def wrapper(*a, **k): for _ in range(times): out = fn(*a, **k) return out return wrapper return deco @repeat(3) def hi(): print("hi") hi() # prints hi three times5 Predict the output: what is the order when decorators are stacked?
hardDecorators apply bottom to top, so the one nearest the function wraps first. At call time the outermost wrapper runs first. In this example, @a above @b means f = a(b(f)).
pythondef a(fn): def w(): print("a before"); fn(); print("a after") return w def b(fn): def w(): print("b before"); fn(); print("b after") return w @a @b def f(): print("f") f() # a before / b before / f / b after / a after6 What happens at definition time versus call time for a decorator?
mediumAt definition time, when Python executes the def, the decorator function runs once and its return value replaces the name. Any print placed in the decorator body, outside the wrapper, therefore appears once at import. Code inside the wrapper runs on every call. This is why decorators used for registration, such as route tables, work at import time.
pythondef deco(fn): print("decorating", fn.__name__) def w(*a, **k): print("calling") return fn(*a, **k) return w @deco def f(): pass # prints: decorating f f(); f() # prints: calling (twice)7 What is functools.lru_cache and when does it help?
mediumlru_cache memoises a function by storing results keyed on its arguments, evicting the least recently used entry when maxsize is reached. It speeds up recursion with overlapping subproblems and pure functions. Arguments must be hashable, the function should have no side effects, and cached values stay in memory. functools.cache is the unbounded shortcut from Python 3.9.
pythonfrom functools import lru_cache @lru_cache(maxsize=None) def fib(n): return n if n < 2 else fib(n - 1) + fib(n - 2) print(fib(80)) # 23416728348467685 print(fib.cache_info().hits > 0) # True8 How do you write a class-based decorator?
hardImplement __init__ to receive the function and __call__ to act as the wrapper. The instance replaces the function, so use functools.update_wrapper(self, fn) to keep metadata. Class-based decorators are convenient when the wrapper needs state, such as a call counter. Note that an instance is not a function, so using it on methods needs __get__ support.
pythonimport functools class Count: def __init__(self, fn): functools.update_wrapper(self, fn) self.fn, self.calls = fn, 0 def __call__(self, *a, **k): self.calls += 1 return self.fn(*a, **k) @Count def f(): pass f(); f() print(f.calls) # 29 What are the built-in decorators @property, @staticmethod and @classmethod?
mediumThey are descriptors applied with decorator syntax. @property turns a method into a computed attribute with optional setter and deleter. @staticmethod stores a plain function in the class without self. @classmethod binds the class as the first argument. See Python OOPs interview questions for worked class examples.
10 Write a retry decorator that retries a function on failure.
mediumAccept the retry count and exception types as decorator arguments, loop up to that many attempts, re-raise the last exception when exhausted, and preserve metadata with wraps. Good answers catch specific exceptions, not a bare except, and mention backoff with time.sleep.
pythonimport time from functools import wraps def retry(times=3, exc=(Exception,), delay=0): def deco(fn): @wraps(fn) def w(*a, **k): for attempt in range(1, times + 1): try: return fn(*a, **k) except exc: if attempt == times: raise time.sleep(delay) return w return deco11 Why does a decorator break when applied to a method, and how do you handle both cases?
hardA function-based wrapper written as wrapper(*args, **kwargs) works on methods, because the instance arrives as the first positional argument in args. Breakage happens with class-based decorators, since an instance of a class with __call__ is not bound as a method. Fix it by implementing __get__ or by using a function wrapper. Also decorators applied to a method run once per class definition, not per instance.
12 What is the difference between a decorator and a context manager?
mediumA decorator wraps a whole function call. A context manager wraps a block with enter and exit logic, used with the with statement. They solve similar problems like timing or locking, and contextlib.contextmanager can produce an object that works as both through ContextDecorator.
13 Predict the output: a decorator that forgets to return the wrapped function's result.
hardIf the wrapper calls fn(*args) but does not return it, the decorated function always returns None, even though the original returned a value. Another variant is returning wrapper() with parentheses, which calls it at definition time and binds the name to its result.
pythondef deco(fn): def w(*a): fn(*a) # missing return return w @deco def add(a, b): return a + b print(add(1, 2)) # None
Frequently asked questions
Do decorators modify the original function?
No. They replace the name with whatever the decorator returns. The original function still exists, reachable through __wrapped__ if wraps was used.
Can I apply more than one decorator to a function?
Yes. They apply from the bottom up and execute from the outside in on each call.
What is the difference between @decorator and @decorator()?
The first passes the function to decorator directly. The second calls decorator first, which must return the real decorator, so it is the pattern for decorators with arguments.
Where are decorators used in real projects?
Web frameworks use them for routes and permissions, test frameworks for fixtures and parametrisation, and application code for caching, retries, logging and timing.
Related guides
More in Programming Language Interview Questions by Language
- Python Exception Handling Interview Questions
- Python File Handling Interview Questions
- Python Generators and Iterators Interview Questions
- Python Interview Questions and Answers
- Python Lambda, Map, Filter and Reduce Interview Questions
- Python List, Dict and Set Interview Questions
- Python Memory Management Interview Questions
- Python Multithreading and Multiprocessing Interview Questions
- Python OOPs Interview Questions
- Python String Interview Questions
- SQL CTE and Recursive Query Interview Questions
- SQL GROUP BY and HAVING Interview Questions