2016-08-03 96 views
0

是否有可能輸出的用戶定義函數的內容作爲一個字符串(不枚舉,但只是函數調用):函數說明返回字符串?

功能:

def sum(x,y): 
    return x+y 

功能的內容作爲一個字符串:

"sum(), return x+y" 

檢查功能可能工作,但它似乎只是爲python 2.5及以下?

+0

爲什麼'除了()'和'不加(個體經營)'? –

+1

'inspect'不適用於Python 2.5或更低版本;你在哪裏讀到的? 「inspect」模塊在最新的Python版本中仍然活躍起來。 –

+0

編輯該問題。 – BlackHat

回答

2

inspect module適用於檢索源代碼,但不限於較老的Python版本。

提供的源是可用的(例如該功能不是在C代碼或交互式解釋定義,或者從一個模塊,用於僅將.pyc字節代碼高速緩存可以是進口),則可以使用:

import inspect 
import re 
import textwrap 

def function_description(f): 
    # remove the `def` statement. 
    source = inspect.getsource(f).partition(':')[-1] 
    first, _, rest = source.partition('\n') 
    if not first.strip(): # only whitespace left, so not a one-liner 
     source = rest 
    return "{}(), {}".format(
     f.__name__, 
     textwrap.dedent(source)) 

演示:

>>> print open('demo.py').read() # show source code 
def sum(x, y): 
    return x + y 

def mean(x, y): return sum(x, y)/2 

def factorial(x): 
    product = 1 
    for i in xrange(1, x + 1): 
     product *= i 
    return product 

>>> from demo import sum, mean, factorial 
>>> print function_description(sum) 
sum(), return x + y 

>>> print function_description(mean) 
mean(), return sum(x, y)/2 

>>> print function_description(factorial) 
factorial(), product = 1 
for i in xrange(1, x + 1): 
    product *= i 
return product 
+0

我得到以下錯誤:提高IOError('無法獲取源代碼') IOError:無法獲取源代碼 – BlackHat

+0

@BlackHat:那麼沒有源代碼來檢索。您是否在交互式解釋器中定義了該功能?然後沒有任何源代碼需要檢查。 –

+0

我明白你的意思了。謝謝。 – BlackHat