带有内置函数的 Python inspect.getargspec [英] Python inspect.getargspec with built-in function
问题描述
我试图找出从模块中检索到的方法的参数.我发现了一个带有方便函数 getargspec
的 inspect
模块.它适用于我定义的函数,但不适用于来自导入模块的函数.
I'm trying to figure out the arguments of a method retrieved from a module.
I found an inspect
module with a handy function, getargspec
.
It works for a function that I define, but won't work for functions from an imported module.
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
是专为本地函数设计的还是我做错了什么?
Is inspect.getargspec
designed only for local functions or am I doing something wrong?
推荐答案
对于用 C 而不是 Python 实现的函数,不可能获得此类信息.
It is impossible to get this kind of information for a function that is implemented in C instead of Python.
这样做的原因是,除了解析(自由格式)文档字符串之外,无法找出该方法接受的参数,因为参数是以(有点)类似 getarg 的方式传递的——即不可能找到在不实际执行函数的情况下找出它接受的参数.
The reason for this is that there is no way to find out what arguments the method accepts except by parsing the (free-form) docstring since arguments are passed in a (somewhat) getarg-like way - i.e. it's impossible to find out what arguments it accepts without actually executing the function.
这篇关于带有内置函数的 Python inspect.getargspec的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!