- Home
- Interview Questions
- Python
- 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
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:
- Factory (outermost): receives the decorator arguments, such as
timesordelay. It runs once, at decoration time. - Decorator (middle): receives the function being decorated. It also runs once, at decoration time.
- Wrapper (innermost): receives
*args, **kwargsand 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 @retryCommon mistakes
- Dropping the parentheses: writing
@retrywhen the factory requires a call. The function gets passed astimes, and the name ends up bound to the innerdecorator. 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)orreturn wrapper. This silently producesNone. - 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 deffunctions? - 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
Related Questions
- How is a lambda different from an anonymous inner class in Java beyond shorter syntax? · Java · 1 ans
- Why does a for loop with var and setTimeout print the same value every time? · JavaScript · 1 ans
- Why do lambdas created inside a loop all return the last loop value in Python? · Python · 1 ans
- Why does using a mutable default argument like a list cause bugs in Python? · Python · 1 ans
- How do positional-only (/) and keyword-only (*) parameters work in Python function signatures? · Python · 1 ans
- What is broadcasting in NumPy and what rules decide whether two arrays can be combined? · Python · 1 ans
- Why does Pandas raise SettingWithCopyWarning and how do you fix chained assignment correctly? · Python · 1 ans
- What is the difference between assignment, shallow copy and deep copy in Python? · Python · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)