如何检查函数/方法采用哪些参数? [英] How to check which arguments a function/method takes?

查看:84
本文介绍了如何检查函数/方法采用哪些参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为使我在Python中构建的几个模块保持一致,我想进行一些自动代码检查.为此,我想检查模块的功能以及功能所采用的参数.我可以使用hasattr()来检查模块是否实际包含预期的功能.到目前为止一切顺利.

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?

推荐答案

您可以使用

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

演示:

>>> 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']

在Python 3中,您要使用 inspect.getfullargspec() ,因为此方法支持Python 3函数自变量的新功能:

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()应该被认为在Python 3中已弃用.

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

Python 3.4添加了 对象:

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.

这篇关于如何检查函数/方法采用哪些参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆