Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question

How do you write a decorator that itself accepts arguments, like `@retry(times=3)`?

Answer

A decorator that takes arguments needs one extra layer of nesting: the outermost function accepts the decorator's own arguments and returns the actual decorator function, which accepts the target function and returns the wrapper, which accepts the target function's arguments at call time. So `@retry(times=3)` first calls `retry(times=3)`, which returns the real decorator, and that decorator is then applied to the function immediately below it, exactly like a normal argument-less decorator would be.

Strong answer includes

  • needs an extra outer layer that returns the real decorator
  • outer layer takes the decorator's own arguments
  • the returned decorator is then applied to the function as usual

Practical example

Python example
def retry(times):
    if times < 1:
        raise ValueError("times must be at least 1")
    def decorator(func):
        def wrapper(*args, **kwargs):
            for attempt in range(times):
                try:
                    return func(*args, **kwargs)
                except Exception:
                    if attempt == times - 1:
                        raise
        return wrapper
    return decorator

defines a three-level decorator factory.

#decorators#advanced

Sources

The Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semantics