Dean Christian Armada Dean Christian Armada - 1 year ago 63
Python Question

Creating a decorator depends with the kwargs argument as parameters

I have a code:

from functools import wraps

def my_decorator(f):
def wrapper(*args, **kwargs):
print kwargs["name"] # Should display Dean Armada
print 'Calling decorated function'
return f(*args, **kwargs)
return wrapper

@my_decorator(name="Dean Armada")
def example():
print 'Called example function'


What I want to achieve is for my decorator to depend on the kwargs arguments as all of its parameter.. My code above throws this error

my_decorator() got an unexpected keyword argument 'name'

Answer Source

You can have separate arguments for your decorator in the following way:

from functools import wraps

def my_decorator(**decorator_kwargs):  # the decorator
    print decorator_kwargs['name']

    def wrapper(f):  # a wrapper for the function
        def decorated_function(*args, **kwargs):  # the decorated function
            print 'Calling decorated function'
            return f(*args, **kwargs)
        return decorated_function
    return wrapper

@my_decorator(name='Dean Armada')
def example(string):
    print string

if __name__ == '__main__':
    example('Print this!')

Running this produces the output:

Dean Armada
Calling decorated function
Print this!

Also note that decorator_kwargs is accessible from wrapper and decorated_function as well if needed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download