EsotericVoid
EsotericVoid

Reputation: 2576

Inject **kwargs into a function in order to avoid TypeError

I'm working with this module that has a function without **kwargs in the signature, thus if I pass a parameter that is not there I receive a TypeError. I would like to call this function by unpacking a dict in a way that the parameters not present in the signature are just ignored (let's assume that since it's an external module I cannot change the signature).

I found this answer that suggests using the inspect module to remove all the arguments that are not present in the signature ,from the dict being passed. Is this still the only way to do this or has something changed in the latest Python versions?

Upvotes: 1

Views: 303

Answers (1)

EsotericVoid
EsotericVoid

Reputation: 2576

I solved this using the inspect module inside a decorator, since there doesn't seem to be another way around it. I'm on Python 3.6.2.

import inspect
from functools import wraps

def inject_kwargs(f):
    @wraps(f)
    def wrapped(*args, **kwargs):
        argspec = inspect.getfullargspec(f)
        if not argspec.varkw:  # function does not accept arbitrary keywords arguments
            return f(*args, **{k: kwargs[k] for k in kwargs if k in argspec.args})
        else:
            return f(*args, **kwargs)

    return wrapped

@inject_kwargs
def test(foo=None, bar=None):
    print(foo, bar)

x = {'bar': 1, 'baz': 2}
test(**x)  # now prints (None, 1) without raising any error

Upvotes: 1

Related Questions