How to check which arguments a function/method takes? [duplicate]

倾然丶 夕夏残阳落幕 提交于 2019-12-22 09:49:46

问题


To keep a couple modules I'm building in Python a bit consistent I want to do some automated code checking. For this I want to check the modules for their functions and the arguments the functions take. I can use hasattr() to check whether the module actually contains the expected functions. So far so good.

I now want to see which arguments the functions take. It would be enough to simply see the variable names. I have no idea how I would be able to do this though. Does anybody know how I can get the names of the arguments a function takes?


回答1:


You can use inspect.getargspec() to see what arguments are accepted, and any default values for keyword arguments.

Demo:

>>> def foo(bar, baz, spam='eggs', **kw): pass
... 
>>> import inspect
>>> inspect.getargspec(foo)
ArgSpec(args=['bar', 'baz', 'spam'], varargs=None, keywords='kw', defaults=('eggs',))
>>> inspect.getargspec(foo).args
['bar', 'baz', 'spam']

In Python 3, you want to use inspect.getfullargspec() as this method supports new Python 3 function argument features:

>>> def foo(bar: str, baz: list, spam: str = 'eggs', *, monty: str = 'python', **kw) -> None: pass
... 
>>> import inspect
>>> inspect.getfullargspec(foo)
FullArgSpec(args=['bar', 'baz', 'spam'], varargs=None, varkw='kw', defaults=('eggs',), kwonlyargs=['monty'], kwonlydefaults={'monty': 'python'}, annotations={'baz': <class 'list'>, 'return': None, 'spam': <class 'str'>, 'monty': <class 'str'>, 'bar': <class 'str'>})

inspect.getargspec() should be considered deprecated in Python 3.

Python 3.4 adds the inspect.Signature() object:

>>> inspect.signature(foo)
<inspect.Signature object at 0x100bda588>
>>> str(inspect.signature(foo))
"(bar:str, baz:list, spam:str='eggs', *, monty:str='python', **kw) -> None"
>>> inspect.signature(foo).parameters
mappingproxy(OrderedDict([('bar', <Parameter at 0x100bd67c8 'bar'>), ('baz', <Parameter at 0x100bd6ea8 'baz'>), ('spam', <Parameter at 0x100bd69f8 'spam'>), ('monty', <Parameter at 0x100bd6c28 'monty'>), ('kw', <Parameter at 0x100bd6548 'kw'>)]))

and many more interesting options to play with signatures.



来源:https://stackoverflow.com/questions/23228664/how-to-check-which-arguments-a-function-method-takes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!