Python inspect.getargspec具有内置函数

时间:2012-07-05 11:15:38

标签: python function methods arguments inspect

我正在试图弄清楚从模块中检索的方法的参数。 我找到了一个带有便捷功能inspect的{​​{1}}模块。 它适用于我定义的函数,但不适用于导入模块的函数。

getargspec

我会收到这样的错误:

import math, inspect
def foobar(a,b=11): pass
inspect.getargspec(foobar)  # this works
inspect.getargspec(math.sin) # this doesn't

File "C:\...\Python 2.5\Lib\inspect.py", line 743, in getargspec raise TypeError('arg is not a Python function') TypeError: arg is not a Python function 是否仅针对本地功能而设计还是我做错了什么?

2 个答案:

答案 0 :(得分:12)

对于用C而不是Python实现的函数,不可能得到这种信息。

原因是没有办法找出方法接受的参数,除非通过解析(自由格式)文档字符串,因为参数以(有点)类似于getarg的方式传递 - 即它不可能找到在没有实际执行函数的情况下接受它接受的参数。

答案 1 :(得分:2)

您可以获取此类函数/方法的doc字符串,这些函数/方法几乎总是包含与getargspec相同类型的信息。 (即,参数名称,参数号,可选值,默认值)。

在你的例子中

import math
math.sin.__doc__

给出

"sin(x)

Return the sine of x (measured in radians)"

不幸的是,有几种不同的标准在运作。见What is the standard Python docstring format?

您可以检测正在使用哪个标准,然后以这种方式获取信息。从上面的链接看起来pyment可能有助于做到这一点。