cfpete cfpete - 1 year ago 139
Python Question

how to do a conditional decorator in python 2.6

Is it possible to decorator a function conditionally. For example, I want to decorate the function

with a timer function (
) only doing_performance_analysis is
(see the psuedo-code below).

if doing_performance_analysis:
def foo():
do something, timeit function will return the time it takes
def foo():

Answer Source

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:

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)

Now you can use it like this:

@conditional_decorator(timeit, doing_performance_analysis)
def foo():
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download