Advertisement

Decorators interview questions and answers

15 Decorators interview questions for Python roles, each with a model answer, examples and likely follow-ups.

15 questions
Advertisement

15 questions

Q11 Advanced Save

How do you preserve a decorated function's original SIGNATURE (parameter names, defaults) for introspection tools, beyond what functools.wraps alone provides?

functools.wraps copies __name__/__doc__/__module__ but the wrapper's ACTUAL call signature (as seen by inspect.signature()) is still `(*args, **kwargs)` unless you also explicitly copy or reconstruct the __wrapped__ attribute (which wraps() DOES set) — inspect.signature() automatically follows __wrapped__ to find the TRUE original signature.
import inspect, functools

def logged(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

@logged
def add(a: int, b: int) -> int:
    return a + b

print(inspect.signature(add))  # '(a: int, b: int) -> int' -- correctly follows __wrapped__
Real-world example
Ensuring IDE autocomplete and documentation tools correctly show a decorated function's real parameter list, not '(*args, **kwargs)'.
Likely follow-ups
  • How does inspect.signature() actually use the __wrapped__ attribute internally to find the true original signature?
Type Hints
Q12 Advanced Save

How would you implement a thread-safe caching decorator that correctly handles concurrent calls from multiple threads?

Protect the shared cache dictionary with a threading.Lock inside the decorator, ensuring only one thread can check-and-update the cache at a time — without this, two threads could simultaneously see a cache miss and both compute (and potentially double-write) the same expensive result, or corrupt the dict during concurrent modification.
import threading, functools

def thread_safe_cache(func):
    cache = {}
    lock = threading.Lock()
    @functools.wraps(func)
    def wrapper(*args):
        with lock:
            if args not in cache:
                cache[args] = func(*args)
            return cache[args]
    return wrapper
Real-world example
Building a thread-safe memoization decorator for a function called concurrently from multiple worker threads in a web server.
Likely follow-ups
  • Does functools.lru_cache already provide this same thread-safety guarantee internally, or would you still need to add your own locking?
Concurrency (asyncio/threading/multiprocessing)
Q13 Advanced Save

How do you write a decorator that works correctly on an async function (coroutine), given that a regular decorator's wrapper would break 'await' usage?

The wrapper function itself must ALSO be declared 'async def' and use 'await' when calling the original coroutine — a plain synchronous wrapper calling an async function without awaiting it would just return an un-awaited coroutine object instead of the actual result.
import functools

def async_logged(func):
    @functools.wraps(func)
    async def wrapper(*args, **kwargs):  # must ALSO be async
        print(f"Calling {func.__name__}")
        result = await func(*args, **kwargs)  # must await the coroutine
        return result
    return wrapper

@async_logged
async def fetch_data():
    await asyncio.sleep(1)
    return "data"
Real-world example
Adding logging or timing behavior consistently to async functions in an asyncio-based application.
Likely follow-ups
  • How would you write a SINGLE decorator that correctly handles BOTH sync and async functions automatically?
Async Generators & Async Context Managers
Q14 Advanced Save

How would you build a decorator-based plugin/registration system, similar to how Flask's @app.route() registers view functions?

Have the decorator STORE a reference to the decorated function in a shared registry (a dict or list, often a class attribute or module-level variable) as a SIDE EFFECT, while returning the ORIGINAL function UNCHANGED — the decorator's primary purpose here is registration, not wrapping/modifying behavior.
routes = {}

def route(path):
    def decorator(func):
        routes[path] = func  # registers the function, but doesn't wrap/modify it
        return func           # returns the ORIGINAL function, unchanged
    return decorator

@route("/users")
def list_users():
    return ["Sam", "Alex"]

print(routes["/users"]())  # calls list_users() via the registry
Real-world example
Building a lightweight routing system, event handler registry, or plugin discovery mechanism using decorators purely for registration.
Likely follow-ups
  • Why does this registration-style decorator return the ORIGINAL function unchanged, unlike a typical wrapping decorator?
Modules & Packaging
Q15 Intermediate Save

How do you use functools.lru_cache to add memoization to a function with a single decorator?

@functools.lru_cache(maxsize=N) automatically caches a function's return values keyed by its arguments, returning the cached result on repeated calls with the same arguments instead of recomputing — maxsize controls how many distinct argument combinations are cached before older ones are evicted (LRU policy).
from functools import lru_cache

@lru_cache(maxsize=128)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

fibonacci(30)  # fast, thanks to automatic caching of overlapping subcalls
Real-world example
Speeding up a recursive Fibonacci calculation or an expensive pure computation called repeatedly with the same arguments.
Likely follow-ups
  • What does passing maxsize=None to lru_cache do, and when would that be risky for memory usage?
functools & Functional Programming Tools

Showing 11–15 of 15