1. Home
  2. Interview Questions
  3. Python
  4. How do you write a Python decorator that accepts its own arg…

Try answering first

In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.

1 Answer

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best answer ·

Short answer: You write a decorator factory: an outer function that takes the arguments and returns the actual decorator, which then wraps the function. So @retry(times=3) first calls retry(times=3), and the decorator it returns is applied to the function.

Detailed explanation

A plain decorator is a callable that takes a function and returns a replacement. The line @deco above def f is shorthand for f = deco(f). With arguments, the expression after @ is evaluated first. So @deco(x) means f = deco(x)(f). That is why you need one extra layer of nesting.

A parameterised decorator therefore has three levels:

  1. Factory (outermost): receives the decorator arguments, such as times or delay. It runs once, at decoration time.
  2. Decorator (middle): receives the function being decorated. It also runs once, at decoration time.
  3. Wrapper (innermost): receives *args, **kwargs and runs on every call to the decorated function.

Closures make this work. The wrapper can read times and func because they are captured from the enclosing scopes, even after the outer functions have returned.

Always apply functools.wraps(func) to the wrapper. It copies __name__, __doc__, __module__ and __qualname__, updates __dict__, and sets __wrapped__. Without it, logging, debugging, documentation tools and inspect.signature see the name wrapper instead of your function.

Typical real-world uses are retry with a configurable attempt count, rate limiting, role-based access checks such as @require_role('admin'), caching with a size limit (as in functools.lru_cache(maxsize=128)), and route registration in web frameworks (Flask's @app.route('/path')).

Example

import functools
import time

def retry(times=3, delay=0.5, exceptions=(Exception,)):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(1, times + 1):
                try:
                    return func(*args, **kwargs)
                except exceptions as exc:
                    if attempt == times:
                        raise
                    print(f'Attempt {attempt} failed: {exc}; retrying')
                    time.sleep(delay)
        return wrapper
    return decorator

calls = {'n': 0}

@retry(times=3, delay=0.1, exceptions=(ConnectionError,))
def flaky():
    calls['n'] += 1
    if calls['n'] < 3:
        raise ConnectionError('server busy')
    return 'ok'

print(flaky())          # two retry messages, then: ok
print(flaky.__name__)   # flaky (thanks to functools.wraps)

# Equivalent without @ syntax:
# flaky = retry(times=3, delay=0.1, exceptions=(ConnectionError,))(flaky)

Only ConnectionError triggers a retry. Any other exception propagates immediately. On the last attempt, the bare raise re-raises the original error with its traceback intact.

Some libraries let you write both @retry and @retry(times=5). The usual approach is to make the first parameter optional, then check whether a callable was passed directly:

def retry(func=None, *, times=3):
    def decorator(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            ...
        return wrapper
    if func is None:
        return decorator      # used as @retry(...)
    return decorator(func)    # used as @retry

Common mistakes

  • Dropping the parentheses: writing @retry when the factory requires a call. The function gets passed as times, and the name ends up bound to the inner decorator. Calling it then returns a wrapper instead of running your code, and nothing errors out at definition time.
  • Putting per-call state in the wrong layer: a mutable counter or list created in the factory or decorator layer is shared by every call, and across threads. Per-call state belongs inside the wrapper.
  • Forgetting to return values: leaving out return func(*args, **kwargs) or return wrapper. This silently produces None.
  • Skipping functools.wraps: this breaks introspection, stack traces that show the function name, and tools that rely on the function's metadata.

Follow-up questions

  • How would you implement the same parameterised decorator as a class using __init__ and __call__?
  • How would you make this retry decorator work with async def functions?
  • In what order are stacked decorators with arguments evaluated and applied?

Interview tip: Before writing any code, say out loud that @deco(x) means f = deco(x)(f). That one line shows the interviewer you understand why the extra layer exists.

Reviewed by the Interview Questions editorial team · Last updated

How well did you know this?

Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.

Your Answer

More medium Python questions

All medium questions →

Related Questions

‹
Q5 of 10 · Python
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA