How would you write a decorator that takes arguments?

Python advanced features · Experienced

Model answer

Add one more layer: a function that takes the arguments and returns the real decorator, which wraps the function. For example retry(times=3) returns decorator(func), which returns wrapper(*args, **kwargs). Use functools.wraps on the wrapper.

Learn this topic

The Python Standard Library: Dates, Counter, Statistics and More in the course Python for Beginners: Learn to Code with Real Projects.

Sign in to add your own answer.

More questions