Some uncontroversial background experimentation up front:
import inspect
def func(foo, bar):
pass
print(inspect.signature(func)) # Prints "(foo, bar)" like you'd expect
def decorator(fn):
def _wrapper(baz, *args, *kwargs):
fn(*args, **kwargs)
return _wrapper
wrapped = decorator(func)
print(inspect.signature(wrapped)) # Prints "(baz, *args, **kwargs)" which is totally understandable
The Question
How can implement my decorator so that print(inspect.signature(wrapped))
spits out "(baz, foo, bar)"? Can I build _wrapper
dynamically somehow by adding the arguments of whatever fn
is passed in, then gluing baz
on to the list?
The answer is NOT
def decorator(fn):
@functools.wraps(fn)
def _wrapper(baz, *args, *kwargs):
fn(*args, **kwargs)
return _wrapper
That give "(foo, bar)" again - which is totally wrong. Calling wrapped(foo=1, bar=2)
is a type error - "Missing 1 required positional argument: 'baz'"
I don't think it's necessary to be this pedantic, but
def decorator(fn):
def _wrapper(baz, foo, bar):
fn(foo=foo, bar=bar)
return _wrapper
Is also not the answer I'm looking for - I'd like the decorator to work for all functions.