Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python check if function accepts **kwargs

Tags:

python

is there a way to check if a function accepts **kwargs before calling it e.g.

def FuncA(**kwargs):
    print 'ok'

def FuncB(id = None):
    print 'ok'

def FuncC():
    print 'ok'

args = {'id': '1'}

FuncA(**args)
FuncB(**args)
FuncC(**args)

When I run this FuncA and FuncB would be okay but FuncC errors with got an unexpected keyword argument 'id' as it doesn't accept any arguments

like image 301
John Avatar asked Feb 17 '11 11:02

John


People also ask

How do you pass a Kwargs argument in Python?

Python **kwargs In the function, we use the double asterisk ** before the parameter name to denote this type of argument. The arguments are passed as a dictionary and these arguments make a dictionary inside function with name same as the parameter excluding double asterisk ** .

How do you use Kwargs in a function?

The double asterisk form of **kwargs is used to pass a keyworded, variable-length argument dictionary to a function. Again, the two asterisks ( ** ) are the important element here, as the word kwargs is conventionally used, though not enforced by the language.

How do I get key value from Kwargs?

get() which accepts a default parameter (itself defaulting to None ), so that kwargs. get("errormessage") returns the value if that key exists and None otherwise (similarly kwargs.

What is Kwarg?

**kwargs stands for keyword arguments. The only difference from args is that it uses keywords and returns the values in the form of a dictionary. Now, let's write a normal function and pass arguments through args and kwargs.


2 Answers

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

It's easier to ask forgiveness than permission.

like image 91
Katriel Avatar answered Oct 16 '22 16:10

Katriel


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.

like image 34
9000 Avatar answered Oct 16 '22 18:10

9000