I want to have a decorator, that takes only *args
and **kwargs
as input, makes some changes to them and then call the original function with positional and named arguments from the decorated function unchanged.
The change to the arguments is just to prepend --
to the args
and also to the keys of the dict
of kwargs
.
E.g. I want to use this decorator like this:
from decorator import decorator
@decorator
def prepare_opts(decorated_func, *args, **kwargs):
prepared_args = prepare_single_opt_keys(args)
prepared_kwargs = prepare_named_opt_keys(kwargs)
return decorated_func(*prepared_args, **prepared_kwargs)
@my_decorator
def func1(pos1, pos2, *args, named1=None, **kwargs):
...do stuff
Here pos1
, pos2
and named1
should be ignored by the decorator.
So a call to func1
like this:
func1('foo', 'bar', 'foo', 'bar', named1='foobar', foo='bar')
Should call the decorated function like this:
func1('foo', 'bar', named1='foobar', ('--foo', '--bar'), {'--foo': 'bar'})
But this can obviously not work, as the decorator passes ('--foo', '--bar', '--foo', '--bar')
to pos1
and {'--named1': 'foobar', '--foo': 'bar'}
to pos2
.
I know that I can get the correct arguments if I change the decorator to:
@decorator
def prepare_opts(decorated_func, pos1, pos2, *args, named1, **kwargs):
prepared_args = prepare_single_opt_keys(args)
prepared_kwargs = prepare_named_opt_keys(kwargs)
return decorated_func(pos1, pos2, *prepared_args, named1, **prepared_kwargs)
But the problem here is, I want the decorator to work with a lot of different functions, that all have a different number of positional and named parameters and additional *args
and **kwargs
.
Summary of my question: Is there a way to parse *args
and **kwargs
in a decorator without touching any of the positional and named arguments of the decorated function and without consuming those in the *args
/**kwargs
-Arguments of my Decoratorfunction?