Distinguish between f () and f (** kwargs) in Python 2.7

I would like to know if a function was declared like f()or f(**kwargs)in Python 2.7, so I know if it can accept arbitrary keyword arguments ... but invoke.getargspec.args () returns [] in both cases. Is there any way to do this?

+4
source share
1 answer

Instead, you need to look inspect.getargspec().keywords. If Noneno is specified **kwargs.

From the inspect.getargspec()documentation :

varargs and keywords are the names of the arguments *and **or None.

Demo:

>>> import inspect
>>> def foo(): pass
... 
>>> def bar(**kwargs): pass
... 
>>> inspect.getargspec(foo).keywords is None
True
>>> inspect.getargspec(bar).keywords is None
False
>>> inspect.getargspec(bar).keywords
'kwargs'
+9
source

All Articles