【问题标题】:Return Function description as string?将函数描述作为字符串返回?
【发布时间】:2016-08-03 15:15:23
【问题描述】:

是否可以将用户自定义函数的内容输出为字符串(不是枚举,只是函数调用):

功能:

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

函数内容为字符串:

"sum(), return x+y"

inspect 功能可能有效,但似乎只适用于 python 2.5 及以下版本?

【问题讨论】:

  • 为什么是addition() 而不是addition(self)
  • inspect 不适用于 Python 2.5 或更低版本;你在哪里读到的? inspect 模块在最新的 Python 版本中是活跃的。
  • 编辑了问题。
  • 对,那为什么是sum() 而不是sum(x, y)
  • 对于多于一行代码的函数应该怎么办?

标签: python python-2.7 function introspection


【解决方案1】:

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

【讨论】:

  • 我得到以下错误:raise IOError('could not get source code') IOError: could not get source code
  • @BlackHat:那么就没有源代码可以检索了。您是否在交互式解释器中定义了函数?那么就没有源代码需要检查了。
  • 我明白你的意思。谢谢。
猜你喜欢
  • 1970-01-01
  • 2012-03-27
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 2012-08-20
  • 1970-01-01
  • 2017-01-21
  • 2020-07-17
相关资源
最近更新 更多