Is it possible to decorate a function conditionally? For example, I want to decorate the function foo() with a timer function (timeit), but only when doing_performance_analysis condition is True, like this:
if doing_performance_analysis:
@timeit
def foo():
"""
Do something, e.g. sleep, and let timeit
return the time it takes
"""
time.sleep(2)
else:
def foo():
time.sleep(2)
Decorators are simply callables that return a replacement, optionally the same function, a wrapper, or something completely different. As such, you could create a conditional decorator:
Now you can use it like this:
The decorator could also be a class:
Here the
__call__method plays the same role as the returneddecorator()nested function in the first example, and the closed-overdecandconditionparameters here are stored as arguments on the instance until the decorator is applied.