【问题标题】:Get return elements of a function [closed]获取函数的返回元素[关闭]
【发布时间】:2018-01-21 08:29:13
【问题描述】:

有没有办法自省函数返回的变量名? 例如。

def foo():
    x = 10
    y = 20
    return x,y 

我正在寻找一种方法来查看返回变量名称"x""y"。有没有一种干净的方法可以做到这一点?

【问题讨论】:

  • 您想看到x, y 作为答案吗?如果函数中有超过 1 个 return 语句怎么办?
  • 只是return [x,y]?我错过了什么吗?
  • 这是一件非常困难的事情,因为函数可以采用许多分支,从而导致不同的返回语句。
  • 如果我理解正确,我认为 OP 对于给定函数希望返回变量的名称和返回的变量计数。
  • @VeltzerDoron 是perfectly possible,不会评论pythonic,没有上下文:)

标签: python python-3.x return introspection


【解决方案1】:

这通常是不可能的。考虑函数:

def foo(x, y):
    if x < y:
        return x
    else:
        return x, y

这里我们有一个函数可以有条件地返回 1 个值或 2 个值(具有不同的名称)。

如果您的函数有类型注释,那么您可以使用inspect.getfullargspec 获取返回类型:

def foo(x: int) -> int:
    return x + 2

inspect.getfullargspec(foo).annotations['return']

返回

int

即您指定的函数将返回的类型。

注意:因为它们是固定的,可以使用相同的方法获取函数参数的名称/默认值。 IE。 inspect.getfullargspec(foo).args 返回['x']

【讨论】:

  • 我借用了你的“硬”例子。我希望你不介意(相应地投票和归因)。
  • @user8371915 不用担心。
【解决方案2】:

一点ast 转换应该可以让你到达那里。一个简单的实现可以这样完成:

import inspect
import ast 

def get_return_ids(f):
    def get_ids(elt):
        """Extract identifiers if present. If not return None"""
        if isinstance(elt, (ast.Tuple, )):
            # For tuple get id of each item if item is a Name
            return [x.id for x in elt.elts if isinstance(x, (ast.Name, ))]
        if isinstance(elt, (ast.Name, )):
            return [elt.id]

    # Get source and parse AST
    (tree, ) = ast.parse(inspect.getsource(f)).body

    # Find all return statements
    rs = [
        node for node in ast.walk(tree) if isinstance(node, (ast.Return, ))
    ]

    return [get_ids(r.value) for r in rs]

示例用法:

>>> get_return_ids(foo)
[['x', 'y']]

具有更复杂的功能(借用形式Alex'sanswer):

>>> def bar(x, y):
...     if x < y:
...         return x
...     else:
...         return x, y
...     
>>> get_return_ids(bar)
[['x'], ['x', 'y']]

在目前的形式中,它仅支持一小部分场景,但您可以根据需要对其进行扩展。

【讨论】:

    猜你喜欢
    • 2012-02-11
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 2017-04-18
    相关资源
    最近更新 更多