是否可以将用户定义函数的内容输出为字符串(不是枚举,而只是函数调用):
功能:
def sum(x,y):
return x+y
函数内容为字符串:
"sum(), return x+y"
inspect函数可能有效,但它似乎只适用于python 2.5及以下版本?
答案 0 :(得分:2)
inspect
module适用于检索源代码,但不限于较旧的Python版本。
如果源是可用的(例如,该函数未在C代码或交互式解释器中定义,或者是从只有.pyc
字节码缓存可用的模块导入的),那么您可以使用:< / p>
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