2012-07-05 215 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看起來可能會有所幫助。