2012-07-05 37 views
6

我想弄清楚从模块中检索到的方法的参数。 我发现一个带有便利功能的inspect模块,getargspec。 它适用于我定义的功能,但不适用于导入模块的功能。Python inspect.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 

inspect.getargspec仅用于本地功能设计还是我做错了什么?

+1

是的,它是这样设计的,请参阅http://bugs.python.org/issue1748064 – georg 2012-07-05 11:16:30

回答

11

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

之所以这样做,是因为没有办法找出该方法接受哪些参数,除非通过解析(自由格式)文档字符串,因为参数是以类似于getarg的方式传递的 - 也就是说,找出它接受的参数而不实际执行该函数。

+0

好吧,我回来了。那么,是否有任何肮脏的方式来做到这一点。如果它需要调用该函数,那没关系。 – PeetWc 2013-09-04 10:40:07

+0

**不**,不是。只有在调用函数不会引发异常的情况下,才能暴露一些参数。但这没有用 - 你甚至不知道是否有一些可选的参数,你没有尝试等。 – ThiefMaster 2013-09-04 11:52:16

+0

Alrite。谢谢。我需要找到另一种方式。 – PeetWc 2013-09-04 11:58:16

1

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

在您的例子

import math 
math.sin.__doc__ 

给人

"sin(x) 

Return the sine of x (measured in radians)" 

不幸的是在运行几个不同的标准。请参阅What is the standard Python docstring format?

您可以检测哪些标准正在使用中,然后以这种方式获取信息。从上面的链接看,pyment看起来可能会有所帮助。