Dean Christian Armada Dean Christian Armada - 3 months ago 8
Python Question

Creating a decorator depends with the kwargs argument as parameters

I have a code:

from functools import wraps

def my_decorator(f):
@wraps(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():
"""Docstring"""
print 'Called example function'

example()


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

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
        @wraps(f)
        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.