Interview Q&A · Python · 15 questions in this topic
Decorators — Python Interview Q&A
Decorators from first principles: the wrapper pattern behind them, functools.wraps, decorators with arguments and the ones you already use in production. Part of Decorators · 375 questions in the Python bank.
What is a decorator in Python?
Answer
A decorator is a function that takes another function (or class) as input and returns a modified or wrapped version of it, adding behavior without changing the original function's source code. The @decorator syntax above a function definition is shorthand for func = decorator(func).
Decorators are a direct, practical application of first-class functions, closures, and higher-order functions (all covered in — a decorator is simply a higher-order function that returns a closure wrapping the original.
Example
def shout(func): def wrapper(*args, **kwargs): result = func(*args, **kwargs) return result.upper() return wrapper @shout # equivalent to: greet = shout(greet) def greet(name): return f"hello, {name}" print(greet("ana")) # 'HELLO, ANA'
💡 Say the syntax's exact desugaring out loud — " @shout above def greet is exactly the same as writing greet = shout(greet) right after the function is defined" — it's the single clearest way to prove you understand decorators beyond just using them.
Why are decorators useful? What problem do they solve?
Answer
Decorators let you add cross-cutting behavior (logging, timing, caching, authentication checks, retries) to multiple functions without duplicating that logic inside each one — keeping each function focused purely on its own core responsibility.
Without decorators, adding the same behavior to many functions means either copy-pasting boilerplate into each one, or manually wrapping each call site — both approaches scale badly and are easy to forget. A decorator centralizes that logic in one place, applied declaratively with a single line above each function that needs it.
Example
import time def timed(func): def wrapper(*args, **kwargs): start = time.perf_counter() result = func(*args, **kwargs) print(f"{func.__name__} took {time.perf_counter() - start:.4f}s") return result return wrapper @timed def slow_calculation(): time.sleep(0.1) return 42 @timed def another_function(): time.sleep(0.05) # Both functions get timing "for free," with zero duplicated logic inside either one slow_calculation() another_function()
💡 Frame the value proposition as "separation of concerns" — decorators let the wrapped function stay focused on its actual job, while the decorator owns the cross-cutting behavior entirely separately.
How do you write a basic function decorator?
Answer
Write an outer function that accepts the target function as its parameter, define an inner wrapper function that calls it (adding behavior before/after), and return that wrapper. Use *args, **kwargs in the wrapper so the decorator works with any function signature.
Using *args, **kwargs (from in wrapper is what makes a decorator generic enough to apply to any function, regardless of how many parameters it takes — without it, your decorator would only work on functions matching one specific signature.
Example
def log_call(func): def wrapper(*args, **kwargs): # accepts ANY signature print(f"Calling {func.__name__} with {args}, {kwargs}") result = func(*args, **kwargs) print(f"{func.__name__} returned {result}") return result return wrapper @log_call def add(a, b): return a + b @log_call def greet(name, greeting="Hello"): return f"{greeting}, {name}!" add(3, 4) greet("Ana", greeting="Hi")
💡 If your decorator's wrapper doesn't use *args, **kwargs, mention that limitation upfront — it's a sign you understand the generic use case decorators are meant to support, not just the one example in front of you.
What happens when you stack multiple decorators on one function?
Answer
Decorators are applied bottom-up (the one closest to the function runs first, wrapping it), but they execute topdown at call time (the outermost decorator's code runs first when the function is actually called).
This is a very common source of confusion: "applied bottom-up" describes the order of wrapping at definition time, while "executes top-down" describes what you observe when you actually call the fully decorated function — both statements are true simultaneously, describing two different moments.
Example
def bold(func): def wrapper(): return f"<b>{func()}</b>" return wrapper def italic(func): def wrapper(): return f"<i>{func()}</i>" return wrapper @bold # applied second (outermost) -- wraps italic(greet) @italic # applied first (innermost) -- wraps greet directly def greet(): return "hello" print(greet()) # <b><i>hello</i></b> # Equivalent to: greet = bold(italic(greet))
How do you write a decorator that accepts its own arguments?
Answer
You need three nested levels of functions instead of two: an outer function that accepts the decorator's own arguments, which returns the actual decorator function, which returns the wrapper — often called a "decorator factory."
The extra nesting level exists because @repeat(3) first calls repeat(3), and that call's return value is what actually gets applied as the decorator to the function beneath it — unlike @repeat alone, which would apply repeat itself directly.
Example
def repeat(times): # outer: accepts the decorator's OWN argument def decorator(func): # middle: the actual decorator def wrapper(*args, **kwargs): # inner: wraps the target function for _ in range(times): result = func(*args, **kwargs) return result return wrapper return decorator @repeat(3) # calls repeat(3) first, applies its return value as the decorator def greet(name): print(f"Hello, {name}!") greet("Ana") # Hello, Ana! # Hello, Ana! # Hello, Ana!
💡 Trace through the desugaring explicitly: @repeat(3) on greet becomes greet = repeat(3)(greet) — being able to say this out loud, one call at a time, is what separates candidates who've memorized the pattern from those who understand it.
What is functools.wraps, and why is it important?
Answer
functools.wraps is itself a decorator you apply to your wrapper function, which copies the original function's metadata (__name__, __doc__, __module__, etc.) onto the wrapper — without it, the decorated function "loses its identity" and looks like a generic wrapper in debugging, introspection, and documentation tools.
Without @wraps, every function decorated by the same decorator would report the same name and docstring (whatever wrapper and its docstring happen to be), making debugging, logging, and auto-generated documentation actively misleading.
Example
from functools import wraps def log_call(func): @wraps(func) # preserves func's metadata on wrapper def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper @log_call def calculate_total(items): """Calculate the total price of items.""" return sum(items) print(calculate_total.__name__) # 'calculate_total' -- correct, thanks to @wraps print(calculate_total.__doc__) # 'Calculate the total price of items.' # Without @wraps, both would incorrectly show 'wrapper' and None instead
What breaks specifically when a decorator forgets functools.wraps?
Answer
func.__name__, func.__doc__, func.__module__, and func.__qualname__ all get silently overwritten with the wrapper's own values instead of the original function's — breaking introspection-dependent tools like debuggers, help(), auto-generated docs, and any code that inspects a function's name at runtime.
This is a concrete elaboration of Q156's trap — beyond just cosmetic confusion, some frameworks and libraries actively rely on __name__ for things like registering routes (e.g., web frameworks matching URL handlers by function name) or caching keys, so a missing @wraps can cause genuinely broken behavior, not just confusing debug output.
Example
def bad_decorator(func): def wrapper(*args, **kwargs): # no @wraps applied return func(*args, **kwargs) return wrapper @bad_decorator def process_payment(amount): """Process a payment of the given amount.""" return f"Processed ${amount}" print(process_payment.__name__) # 'wrapper' -- WRONG, lost the real name print(process_payment.__doc__) # None -- WRONG, lost the real docstring import inspect print(inspect.signature(process_payment)) # (*args, **kwargs) -- lost the real signature too!
💡 Mentioning that inspect.signature() also gets corrupted (showing (*args, **kwargs) instead of the real parameter list) goes beyond the commonly cited __name__ / __doc__ issue and shows deeper familiarity with introspection tooling.
How would you write a decorator that works both with and without parentheses?
Answer
Check whether the decorator's first argument is callable (meaning it was used as @my_decorator directly) versus not (meaning it was used as @my_decorator(.) with arguments), and branch accordingly — typically by making the "arguments" parameter optional and detecting which case you're in.
This pattern is genuinely tricky and rarely needed in everyday code, but it shows up in some popular libraries (like pytest.fixture) that support both usage styles for developer convenience.
Example
from functools import wraps def flexible_decorator(func=None, *, prefix="LOG"): def actual_decorator(f): @wraps(f) def wrapper(*args, **kwargs): print(f"[{prefix}] Calling {f.__name__}") return f(*args, **kwargs) return wrapper if func is not None: return actual_decorator(func) # used as @flexible_decorator (no parens) return actual_decorator # used as @flexible_decorator(prefix="...") @flexible_decorator def task_one(): pass @flexible_decorator(prefix="DEBUG") def task_two(): pass task_one() # [LOG] Calling task_one task_two() # [DEBUG] Calling task_two
💡 This is an advanced pattern — if you don't know it cold, it's completely reasonable to say "I'd need to check whether the first argument is callable to detect which call style is being used," which demonstrates the right instinct even without reciting the full implementation.
What are class-based decorators?
Answer
Instead of a nested function, you can implement a decorator as a class whose __init__ stores the wrapped function (or configuration) and whose __call__ method implements the actual wrapping behavior — an alternative approach that's often clearer when the decorator needs to maintain more complex state.
This directly reuses __call__ from, Q109 — a class-based decorator is simply an object that's callable, used in place of a function in the @decorator position. It's especially useful when you want the decorator itself to expose additional methods or attributes beyond just wrapping a call.
Example
class CountCalls: def __init__(self, func): self.func = func self.call_count = 0 # persistent state, cleanly attached to the decorator def __call__(self, *args, **kwargs): self.call_count += 1 print(f"Call #{self.call_count} to {self.func.__name__}") return self.func(*args, **kwargs) @CountCalls def say_hello(): print("Hello!") say_hello() # Call #1 to say_hello / Hello! say_hello() # Call #2 to say_hello / Hello! print(say_hello.call_count) # 2 -- state is directly accessible on the decorator object
💡 Point out the direct trade-off: a function-based decorator with a closure hides its state inside the closure (harder to inspect from outside), while a class-based decorator exposes it naturally as attributes on an object — useful when callers need to access that state directly.
Can you decorate a class itself, not just its methods?
Answer
Yes — a class decorator takes a class as input and returns a class (either the same one, modified, or an entirely different one), letting you add attributes, wrap methods automatically, or perform registration logic at classdefinition time.
Class decorators are less common than function decorators but are used by real tools — @dataclass is itself a class decorator, transforming a plain class definition into one with an auto-generated __init__, __repr__, and __eq__.
Example
def add_greeting(cls): cls.greet = lambda self: f"Hello, I'm a {cls.__name__}" return cls @add_greeting class Robot: pass r = Robot() print(r.greet()) # "Hello, I'm a Robot" -- method added entirely by the decorator # A registration-style class decorator, common in plugin systems PLUGINS = {} def register(cls): PLUGINS[cls.__name__] = cls return cls @register class CSVExporter: pass print(PLUGINS) # {'CSVExporter': <class 'CSVExporter'>}
💡 Naming @dataclass as a real, extremely common class decorator instantly grounds this otherwise abstract-sounding question in something the interviewer almost certainly recognizes and uses themselves.
How do @property, @staticmethod, and @classmethod relate to decorators in general?
Answer
They're all just built-in decorators — the same @ syntax and underlying "wrap this callable" mechanism covered throughout this section, specialized for particular jobs: @property turns a method into a computed attribute, @staticmethod strips the automatic self / cls binding, and @classmethod binds cls instead of self.
Recognizing that these "special" OOP decorators from are built on exactly the same mechanism as a custom @my_decorator you'd write yourself is a good way to demonstrate that you see Python's features as a small set of composable, consistent building blocks rather than a long list of unrelated syntax to memorize.
Example
class Circle: def __init__(self, radius): self.radius = radius @property # a built-in decorator -- same @ mechanism def area(self): return 3.14159 * self.radius ** 2 @staticmethod # also just a decorator def unit_circle(): return Circle(1) @classmethod # also just a decorator def from_diameter(cls, diameter): return cls(diameter / 2) c = Circle(4) print(c.area) # via @property print(Circle.unit_circle().radius) # via @staticmethod print(Circle.from_diameter(10).radius) # via @classmethod
💡 If asked to "implement your own version of @property," this connection is exactly the insight needed — property itself is essentially a descriptor-based class that behaves like a decorator covers descriptors in depth).
How would you write a decorator to measure a function's execution time?
Answer
Record a timestamp before calling the wrapped function, call it, record another timestamp after, and print or log the difference — using time.perf_counter() rather than time.time(), since it's specifically designed for measuring short, precise durations.
This is one of the most commonly requested "write a decorator" live-coding exercises, precisely because it exercises everything covered in this section at once: *args / **kwargs, functools.wraps, and returning the wrapped function's actual result.
Example
import time from functools import wraps def timer(func): @wraps(func) def wrapper(*args, **kwargs): start = time.perf_counter() result = func(*args, **kwargs) elapsed = time.perf_counter() - start print(f"{func.__name__} took {elapsed:.4f} seconds") return result return wrapper @timer def compute_sum(n): return sum(range(n)) compute_sum(10_000_000) # compute_sum took 0.XXXX seconds
💡 Using time.perf_counter() instead of time.time() is a small but telling detail — perf_counter() is monotonic and higher-resolution, specifically intended for measuring elapsed time, while time.time() reflects wall-clock time and can even jump backward (e.g., due to system clock adjustments).
How would you write a caching (memoization) decorator?
Answer
Store previously computed results in a dictionary keyed by the function's arguments; on each call, check the cache first and only call the real function if that exact combination of arguments hasn't been seen before. The standard library already provides this via functools.lru_cache.
Writing your own memoization decorator is a great exercise for understanding the pattern, but in real code you'd almost always reach for functools.lru_cache (or functools.cache in 3.9+) instead of hand-rolling it — it's well-tested, thread-considerations aside, and supports a configurable maximum cache size with least-recentlyused eviction.
Example
from functools import wraps def memoize(func): cache = {} @wraps(func) def wrapper(*args): if args not in cache: cache[args] = func(*args) return cache[args] return wrapper @memoize def slow_square(n): print(f"Computing square of {n}...") return n ** 2 print(slow_square(5)) # Computing square of 5... / 25 print(slow_square(5)) # 25 -- cached, no "Computing..." printed this time # The standard-library equivalent, preferred in real code: from functools import lru_cache @lru_cache(maxsize=128) def fibonacci(n): if n < 2: return n return fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(30)) # fast, thanks to caching each intermediate result
💡 After demonstrating your own memoization decorator, immediately mention functools.lru_cache as the production-ready equivalent — it shows both that you understand the underlying mechanism and that you know not to reinvent well-solved standard-library functionality unnecessarily.
How would you write a retry decorator?
Answer
Wrap the function call in a loop that catches a specified exception, retries up to a maximum number of attempts (optionally waiting between attempts), and re-raises the exception only after all retries are exhausted.
This is a very realistic, commonly requested decorator exercise, since retry logic shows up constantly in real systems calling flaky external services (APIs, databases, network calls) — combining a parameterized decorator (Q155), exception handling, and time.sleep() for backoff.
Example
import time from functools import wraps def retry(max_attempts=3, delay=1, exceptions=(Exception,)): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): for attempt in range(1, max_attempts + 1): try: return func(*args, **kwargs) except exceptions as e: if attempt == max_attempts: raise # exhausted retries -- let it propagate print(f"Attempt {attempt} failed ({e}), retrying...") time.sleep(delay) return wrapper return decorator @retry(max_attempts=3, delay=0.5, exceptions=(ConnectionError,)) def flaky_network_call(): import random if random.random() < 0.7: raise ConnectionError("Network blip") return "Success!" print(flaky_network_call())
💡 Mention exponential backoff (delay *= 2 after each failed attempt) as a natural productiongrade improvement — real retry logic almost never uses a fixed delay, to avoid hammering an already-struggling service.
What are common real-world use cases for decorators?
Answer
Beyond the examples already covered in this section (timing, caching, retries), decorators are widely used for logging, authentication/authorization checks, input validation, rate limiting, and registering functions with a framework (like route handlers in Flask/FastAPI or task definitions in Celery).
Nearly every popular Python web framework and task-queue library exposes its core API through decorators, precisely because decorators let you declaratively attach framework behavior to a plain function without forcing you to inherit from a base class or implement a specific interface.
Example
# Illustrative examples of decorator-driven APIs you've likely seen in real frameworks: # Flask-style route registration # @app.route("/users/<id>") # def get_user(id): ... # FastAPI-style route + validation # @app.get("/items/{item_id}") # def read_item(item_id: int): ... # A simple hand-rolled authorization decorator def require_admin(func): from functools import wraps @wraps(func) def wrapper(user, *args, **kwargs): if not user.get("is_admin"): raise PermissionError("Admin access required") return func(user, *args, **kwargs) return wrapper @require_admin def delete_account(user, account_id): return f"Account {account_id} deleted" delete_account({"is_admin": True}, 42) # works # delete_account({"is_admin": False}, 42) # raises PermissionError
💡 If you've used Flask, FastAPI, Django, pytest, or Celery, naming the specific decorators you've relied on (@app.route, @pytest.fixture, @shared_task) makes this answer concrete and grounded in real project experience rather than a generic list.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission