python check if function accepts **kwargs

try:
    f(**kwargs)
except TypeError:
    #do stuff

It's easier to ask forgiveness than permission.


def foo(a, b, **kwargs):
  pass

import inspect
args, varargs, varkw, defaults = inspect.getargspec(foo)
assert(varkw=='kwargs')

This only works for Python functions. Functions defined in C extensions (and built-ins) may be tricky and sometimes interpret their arguments in quite creative ways. There's no way to reliably detect which arguments such functions expect. Refer to function's docstring and other human-readable documentation.


func is the function in question.

with python2, it's:

inspect.getargspec(func).keywords is not None

python3 is a bit tricker, following https://www.python.org/dev/peps/pep-0362/ the kind of parameter must be VAR_KEYWORD

Parameter.VAR_KEYWORD - a dict of keyword arguments that aren't bound to any other parameter. This corresponds to a "**kwargs" parameter in a Python function definition.

any(param for param in inspect.signature(func).parameters.values() if param.kind == param.VAR_KEYWORD)

Tags:

Python