Return 函数描述为字符串?
Return Function description as string?
是否可以将用户自定义函数的内容输出为字符串(不是枚举,只是函数调用):
函数:
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
是否可以将用户自定义函数的内容输出为字符串(不是枚举,只是函数调用):
函数:
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