2016-08-03 95 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