Interview Q&A · Python · 15 questions in this topic

Decorators — Python Interview Q&A

All Python topics

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

Example.pypython
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

Example.pypython
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

Example.pypython
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.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits