是否有可能输出的用户定义函数的内容作为一个字符串(不枚举,但只是函数调用):函数说明返回字符串?
功能:
def sum(x,y):
return x+y
功能的内容作为一个字符串:
"sum(), return x+y"
检查功能可能工作,但它似乎只是为python 2.5及以下?
是否有可能输出的用户定义函数的内容作为一个字符串(不枚举,但只是函数调用):函数说明返回字符串?
功能:
def sum(x,y):
return x+y
功能的内容作为一个字符串:
"sum(), return x+y"
检查功能可能工作,但它似乎只是为python 2.5及以下?
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
为什么'除了()'和'不加(个体经营)'? –
'inspect'不适用于Python 2.5或更低版本;你在哪里读到的? “inspect”模块在最新的Python版本中仍然活跃起来。 –
编辑该问题。 – BlackHat