Nafiul Islam
Nafiul Islam

Reputation: 82490

On demand decorator?

I have a decorator called Timer, now ideally, to use a decorator like so:

@Timer
def function(...):
    return None

However, this calls Timer all the time function is called. Now of course you can use a decorator like a normal function to do this, when you want to call it under a particular instance:

function = Timer(function)

However, this does not look pretty (I'm picky, I know). So, is there a way to wrap a decorator over a function for say all use cases in a testing file or something? So, something like:

from app import cheese

@Timer  # Syntax error
cheese  # Syntax error

Note, that it only uses the decorator for this particular file, and not all the time, if you had placed it above the actual function definition.

Upvotes: 0

Views: 213

Answers (1)

Corley Brigman
Corley Brigman

Reputation: 12401

If you can enable/disable at the top of the file (i.e. you know when you load the file whether you want them enabled or not), you can use the Enable/Disable Decorator.

if not... you didn't post the source for the decorator, but there's no reason it couldn't reference a global variable for enable/disable in the wrapping code itself. i.e. a decorator looks like this:

@simple_decorator
def my_simple_logging_decorator(func):
    def you_will_never_see_this_name(*args, **kwargs):
        print 'calling {}'.format(func.__name__)
        return func(*args, **kwargs)
    return you_will_never_see_this_name

(from https://wiki.python.org/moin/PythonDecoratorLibrary)

Simply add in a guard for the added code i.e.

@simple_decorator
def my_simple_logging_decorator(func):
    def you_will_never_see_this_name(*args, **kwargs):
# Added/modified code starts here
        if globalvar:
            print 'calling {}'.format(func.__name__)
# End modified code
        return func(*args, **kwargs)
    return you_will_never_see_this_name

Upvotes: 1

Related Questions