In trying to understand a conditional decorator in python I came upon this example. The accepted answer for that question explains how to define a conditional decorator, but not how to use it.
The example code is as follows:
class conditional_decorator(object):
def __init__(self, dec, condition):
self.decorator = dec
self.condition = condition
def __call__(self, func):
if not self.condition:
# Return the function unchanged, not decorated.
return func
return self.decorator(func)
@conditional_decorator(timeit, doing_performance_analysis)
def foo():
time.sleep(2)
But how to use it? I tried the following calls of foo
like this:
doing_performance_analysis=False
foo()
doing_performance_analysis=True
foo()
but I got the following errors:
Traceback (most recent call last):
File "tester.py", line 18, in <module>
@conditional_decorator(timeit, doing_performance_analysis)
NameError: name 'doing_performance_analysis' is not defined
So how does it work correctly?
doing_performance_analysis
. Have you tried defining that name to a boolean?@conditional_decorator()
line.