Python函数内省:在其中提到了作为参数传递的类的成员?

Les*_*ack 3 python function introspection inspect higher-order-functions

假设我有以下功能:

def eggs(a,b,c):
    if c.foo:
        return a + b.bar
    else:
        return c.spam
Run Code Online (Sandbox Code Playgroud)

我想有能够自省通过功能的高阶函数和获取参数的成员通过点语法的代码里面提到的什么,有以下行为:

>>> member_inspector(eggs, 'c')
('foo','spam')

>>> member_inspector(eggs, 'b')
('bar')

>>> member_inspector(eggs, 'a')
()
Run Code Online (Sandbox Code Playgroud)

可以这样做吗?怎么样?

Ale*_*all 5

这是一个基本版本:

import inspect
from textwrap import dedent
import ast

def member_inspector(f, var):
    source = dedent(inspect.getsource(f))
    module = ast.parse(source)
    func = module.body[0]
    result = []
    for stmt in func.body:
        for node in ast.walk(stmt):
            if (isinstance(node, ast.Attribute) and
                    isinstance(node.value, ast.Name) and
                    node.value.id == var):
                result.append(node.attr)
    return result
Run Code Online (Sandbox Code Playgroud)

  • 我可以问你一些解释,也许是一些指向`ast`模块文档的链接,甚至可能是一个"警告"部分?(如果无法访问函数的源代码,不能检测到带有`getattr`或`vars`或`__dict__`的属性访问,则会失效,会被像`foo = c; c.bar这样的赋值绊倒,如果相同的属性被访问两次,它包含在输出中两次,等等.)你的代码很好,但答案不是. (3认同)