GwynBleidD
GwynBleidD

Reputation: 20539

Decorator converting given kwargs to attrs of function

I'm using most of the time construction like this:

def function(some,params):
    pass
function.arg1 = val1
function.arg2 = val2

But it's not perfectly DRY and it keeps annoying if I have dozens of args added to function or method like this and I need for some reason change function name, because I need to change all function into function2 for example. Maybe there is an built in python decorator which I can use like this:

@some_decorator(arg1=val1, arg2=val2, arg3=val3)
def function(some, params):
    pass

It will save me lot of time when changin function name (or copying function with other name). Anyone knows if there is something built in python? I know that creating such decorator is no big deal, but then I must include it in all my projects, so it will be a lot easier to have it built in.

Upvotes: 1

Views: 322

Answers (1)

Alex Shkop
Alex Shkop

Reputation: 2012

This should do the job

from functools import wraps

def some_decorator(arg1, arg2):
    def wrapper(func):

       @wraps(func)
       def inner_wrapper(*args, **kwargs):
           func(*args, **kwargs)

       inner_wrapper.arg1 = arg1
       inner_wrapper.arg2 = arg2
       return inner_wrapper

    return wrapper

Of course you can chage arg1 and arg2 in decorator to **kwargs if this is more convenient.

Upvotes: 1

Related Questions