0

I am trying to implement the following logic:

def decorator(func):
  def func_wrap(*args, **kwargs):
    ** parse inputs such that I get a dictionary where the keys are the function signature keywords and the values are the matching values **
    ** do some preprocess of inputs **
    return func(**new_kwargs)

To me it seem like a super useful use case however I couldn't find any reference online for this. any ideas?

thanks

1 Answers1

2

thanks to @juanpa.arrivillaga referring: Can you determine from a function, args, and kwargs, how variables will be assigned?

with a small adjustment to take care of defaults I got the wanted behavior:

def decorator(func):
  func_signature = inspect.signature(func)
  def func_wrap(*args, **kwargs):
    bound_arguments = func_signature.bind(*args, **kwargs)
    bound_arguments.apply_defaults()
      for k, v in bound_arguments.arguments.items():
        if k in kwargs:
          continue
        kwargs[k] = v
    ** do some preprocess of kwargs **
    return func(**kwargs)

Or in an even more reusable form, as a function:

def parse_all_inputs_as_kwargs(func, args, kwargs):
    bound_arguments = inspect.signature(func).bind(*args, **kwargs)
    bound_arguments.apply_defaults()
    for k, v in bound_arguments.arguments.items():
        if k in kwargs:
            continue
        kwargs[k] = v
    return kwargs