Can you list the keyword arguments a function receives?

A little nicer than inspecting the code object directly and working out the variables is to use the inspect module.

>>> import inspect
>>> def func(a,b,c=42, *args, **kwargs): pass
>>> inspect.getargspec(func)
(['a', 'b', 'c'], 'args', 'kwargs', (42,))

If you want to know if its callable with a particular set of args, you need the args without a default already specified. These can be got by:

def get_required_args(func):
    args, varargs, varkw, defaults = inspect.getargspec(func)
    if defaults:
        args = args[:-len(defaults)]
    return args   # *args and **kwargs are not required, so ignore them.

Then a function to tell what you are missing from your particular dict is:

def missing_args(func, argdict):
    return set(get_required_args(func)).difference(argdict)

Similarly, to check for invalid args, use:

def invalid_args(func, argdict):
    args, varargs, varkw, defaults = inspect.getargspec(func)
    if varkw: return set()  # All accepted
    return set(argdict) - set(args)

And so a full test if it is callable is :

def is_callable_with_args(func, argdict):
    return not missing_args(func, argdict) and not invalid_args(func, argdict)

(This is good only as far as python’s arg parsing. Any runtime checks for invalid values in kwargs obviously can’t be detected.)

Leave a Comment