Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'd like to be able to tell if a function was declared as f() or f(**kwargs) in Python 2.7, so I know whether or not it can accept arbitrary keyword arguments... but invoke.getargspec.args() returns [] in both cases. Is there a way of doing this?

like image 413
Christophe Avatar asked Jan 11 '23 12:01

Christophe


1 Answers

You need to look at inspect.getargspec().keywords instead. If it is None no **kwargs was given.

From the inspect.getargspec() documentation:

varargs and keywords are the names of the * and ** arguments 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'
like image 55
Martijn Pieters Avatar answered Jan 22 '23 04:01

Martijn Pieters