๐ŸŽ‰ 75% of content is free forever โ€” Unlock Premium from $10/mo โ†’
CW
NEWSLIVESearch All Content
๐Ÿ’ผ Servicesโ„น๏ธ Aboutโœ‰๏ธ ContactView Pricing Plansfrom $10

Decorators and Metaclasses in Python Interviews

Python InterviewAdvanced Pythonโญ Premium
Python Interview ยท Difficulty: Hard

Decorators are just functions that take functions

Strip away the @ syntax and a decorator is a callable that receives another callable and returns a replacement. @timer applied to work is rewritten by the interpreter as work = timer(work). Everything else โ€” parameters, stacking, class-based implementations, registration hooks โ€” is an elaboration on that one sentence. Interviewers ask about decorators because they force you to reason about first-class functions, closures, and metadata preservation in a single small program, and because every serious Python codebase uses them for logging, caching, retries, and permissions.

Prerequisites

  • !Functions as first-class objects
  • !Closures and nested functions
  • !Basic functools usage

What You'll Learn

  • 1Write simple and parameterized decorators without losing function metadata
  • 2Explain decorator stacking order and implement class-based decorators
  • 3Build a correct LRU cache decorator and a retry decorator with backoff
  • 4Decide between a metaclass, __init_subclass__, and a plain function for class customization

The metadata trap and functools.wraps

The first bug every decorator author hits: without functools.wraps, the wrapper reports its own name, docstring, and module, so logging, debugging, and test discovery all lie about which function ran. Adding @wraps(func) copies __name__, __doc__, __module__, __qualname__, and __wrapped__ onto the wrapper. Interviewers who have debugged a mysterious stack trace will nod; candidates who skip it will be asked why their decorator broke a library that introspects signatures.

Parameterized decorators add one more layer. If a decorator accepts arguments, you need three nested functions: the outer function collects the parameters and returns the decorator, the middle function captures the target function, and the inner wrapper does the work. The common failure is returning the decorator instead of the decorated function, or forgetting the layers entirely and decorating with the configuration function directly.

python
import time
from functools import wraps


def timed(repeat=1):
    """Decorator factory: run the function, log duration, optionally repeat."""
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            total = 0.0
            result = None
            for _ in range(repeat):
                start = time.perf_counter()
                result = func(*args, **kwargs)
                total += time.perf_counter() - start
            print(f"{func.__name__} took {total:.4f}s over {repeat} run(s)")
            return result
        return wrapper
    return decorator


@timed(repeat=3)
def bulk_insert(rows):
    return sum(1 for _ in rows)

Stacking, ordering, and class-based decorators

When decorators are stacked, Python applies them bottom-up: the closest decorator to the function runs first when the function is called, but it is also the innermost wrapper. Getting the mental model straight matters when one decorator caches and another validates โ€” cache hits must not skip validation, or stale authorized data leaks through. State the order out loud in interviews; half the candidates reverse it under pressure.

Class-based decorators implement __call__ and keep state on the instance, which makes them natural when the decorator needs counters, history, or configuration. A CountCalls wrapper that records call arguments and timestamps is a five-minute whiteboard exercise that impresses. A class-based rate limiter that stores timestamps of recent calls and raises when the window is full shows the same idea with a production flavor. If the decorator must also accept parameters, the class takes the parameters in __init__ and returns a function or another object from __call__ โ€” either shape is acceptable if you can explain it.

State in stacked decorators deserves one more warning. If an inner decorator caches results and an outer decorator authorizes callers, a cache hit inside the inner layer still runs the outer authorization on every call, which is usually what you want. Reverse the order and an unauthorized caller may receive a cached response that was computed for an authorized one. Sketch the call stack on the whiteboard before committing to an order; it takes fifteen seconds and prevents the kind of security-adjacent bug that makes postmortems.

Three decorators worth having in your pocket

The retry decorator wraps a flaky operation, catches exceptions, and retries with exponential backoff, re-raising the last failure when attempts run out. The cache decorator stores results keyed by arguments and exposes cache_info and cache_clear helpers, mirroring functools.lru_cache โ€” mentioning that the standard library already ships the production version demonstrates humility and tool knowledge. The validation decorator inspects numeric arguments before delegating, showing how cross-cutting concerns stay out of business logic. Together they cover most "write a decorator" variants you will face.

python
from functools import wraps


def retry(max_attempts=3, delay=0.5):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            last = None
            for attempt in range(max_attempts):
                try:
                    return func(*args, **kwargs)
                except Exception as exc:
                    last = exc
                    if attempt < max_attempts - 1:
                        import time
                        time.sleep(delay * (2 ** attempt))
            raise last
        return wrapper
    return decorator


class CountCalls:
    """Class-based decorator that counts invocations."""

    def __init__(self, func):
        self.func = func
        self.calls = 0

    def __call__(self, *args, **kwargs):
        self.calls += 1
        return self.func(*args, **kwargs)


@retry(max_attempts=3, delay=0.1)
@CountCalls
def flaky():
    import random
    if random.random() < 0.5:
        raise ConnectionError("try again")
    return "ok"

Metaclasses: when the class itself needs customizing

A metaclass is the class of a class: type creates classes by default, and a custom metaclass intercepts class creation through __new__ or __call__. The two interview-friendly demonstrations are a thread-safe Singleton metaclass that caches instances in a class-level dict, and a validation metaclass that scans the class namespace for fields marked with validators and attaches a validate() method. Both show that metaclasses run at definition time, before any instance exists โ€” which is exactly why they can enforce invariants across an entire framework.

But the mature answer starts with restraint. In modern Python, most metaclass use cases can be replaced by class decorators, which run after the class is created, or by __init_subclass__, which fires whenever a subclass is defined and supports keyword arguments like plugin_name="json". Reserve metaclasses for problems that truly must modify class creation itself โ€” ORM field collection, abstract-base enforcement, registry injection during class body execution. Saying "I would not use a metaclass here, here is the simpler hook" is frequently the strongest answer available.

If you do write one, remember that metaclasses participate in the same method-resolution machinery as ordinary classes: two metaclasses that are incompatible raise a TypeError at class creation, which is exactly why frameworks with deep hierarchies carefully derive their metaclasses from ABCMeta. Also note that type(name, bases, namespace) builds classes dynamically at runtime, which is what import machinery itself calls under the hood โ€” a nice fact to drop when the interviewer asks how a class comes into existence.

python
class PluginMeta(type):
    """Metaclass that auto-registers subclasses by name."""
    registry = {}

    def __new__(mcs, name, bases, namespace, **kwargs):
        cls = super().__new__(mcs, name, bases, namespace)
        alias = kwargs.get("alias")
        if alias:
            mcs.registry[alias] = cls
        return cls


class Serializer(metaclass=PluginMeta):
    def dumps(self, data):
        raise NotImplementedError


class JsonSerializer(Serializer, alias="json"):
    def dumps(self, data):
        import json
        return json.dumps(data)


print(PluginMeta.registry["json"]().dumps({"a": 1}))

Debugging and testing decorated code

Decorators hide the original function behind a wrapper, which confuses stack traces, profilers, and test patching unless metadata is preserved. When debugging decorated code in an interview, mention three practical moves. First, read __wrapped__ โ€” set by functools.wraps โ€” to reach the undecorated function when you need a clean signature or want to call the raw implementation in a test. Second, use unittest.mock.patch against the module attribute, remembering that the name you patch is the decorated object the module actually holds. Third, keep decorators thin: any logic that can fail independently of the wrapped function belongs inside the wrapped function or a helper, so failures do not masquerade as decorator bugs.

There is also a design smell worth recognizing live: decorators that transform return values or change a function's contract make code harder to reason about. Retry, cache, timing, and permission decorators preserve semantics; ones that rewrite arguments or results should be replaced with explicit functions. Naming that boundary shows judgment about where metaprogramming helps and where it starts to hurt.

ConstructWhat it wrapsTypical useNeeds functools.wraps?
Function decoratorA functionLogging, retries, cachingYes
Class decoratorA classRegistration, validation, instrumentationN/A, but set name if you return a wrapper class
Parameterized decoratorA function, with configRate limits, repeated executionYes
MetaclassA class at creation timeORMs, registries, invariantsN/A
init_subclassSubclass definitionPlugin registration without metaclassesN/A

Common Mistakes

Writing decorators without functools.wraps

Fix: Always decorate the wrapper with @wraps(func) so metadata survives

Returning the decorator factory's inner function at the wrong nesting level

Fix: Sketch the three layers: config, decorator, wrapper โ€” then test with and without arguments

Reaching for a metaclass to register plugins

Fix: Try __init_subclass__ first; it supports keyword arguments and runs on subclass definition

Holding strong references to bound methods in event registries

Fix: Use weakref.WeakMethod so listeners can be garbage collected

Best Practices

  • Prove your decorator works by printing __name__ before and after adding wraps
  • State decorator stacking order whenever more than one wraps the same function
  • Prefer functools.lru_cache or functools.cache unless you are asked to implement caching yourself
  • Treat metaclasses as a last resort and say so explicitly in the interview

Interview Questions

Q1: What does functools.wraps do and why does it matter?

It copies the wrapped function's metadata onto the wrapper and sets __wrapped__. Without it, introspection, logging, and frameworks that read signatures see the wrapper instead of the real function.

Q2: How do stacked decorators apply?

Bottom-up: the decorator nearest the function becomes the innermost wrapper. Calls enter through the top decorator, pass through each layer, and reach the original function last.

Q3: When would you use a class decorator instead of a metaclass?

When the customization can happen after the class object exists โ€” registration, wrapping methods, adding attributes. Metaclasses are only needed when creation itself must be intercepted.

Q4: Explain the three layers of a parameterized decorator.

The outer function collects parameters and returns the decorator; the middle function captures the target function; the inner wrapper performs the work around the original call.

Q5: How does @property relate to decorators and descriptors?

@property is a decorator that returns a Property object, which is a data descriptor implementing __get__, __set__, and __delete__. The decorator syntax is sugar for building that descriptor.

Key Takeaways

  • A decorator is a callable taking a callable and returning a replacement
  • functools.wraps is mandatory in production decorators
  • Parameterized decorators need three nested layers; class decorators keep state naturally
  • Retry, cache, and validation decorators cover most real use cases
  • Metaclasses customize class creation; __init_subclass__ usually solves the same problems more simply
  • Properties are descriptors built by decorators โ€” connecting the topics signals depth
๐Ÿ”’

Premium Content

Decorators and Metaclasses in Python Interviews

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

๐ŸŽฏEnd-to-end Projects
๐Ÿ’ผInterview Prep
๐Ÿ“œCertificates
๐ŸคCommunity Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

โ€”
โ˜†โ˜†โ˜†โ˜†โ˜†
0 ratings

Rate & Feedback

Advertisement