Python 函数自省:作为参数传递的 class 的哪些成员在其中被提及?
Python function introspection: what members of a class passed as argument are mentioned inside it?
假设我有如下函数:
def eggs(a,b,c):
if c.foo:
return a + b.bar
else:
return c.spam
我想要一个高阶函数,它能够自省传递的函数,并通过点语法检索代码中提到的参数成员,具有以下行为:
>>> member_inspector(eggs, 'c')
('foo','spam')
>>> member_inspector(eggs, 'b')
('bar')
>>> member_inspector(eggs, 'a')
()
这能做到吗?怎么样?
这是一个基本版本:
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
假设我有如下函数:
def eggs(a,b,c):
if c.foo:
return a + b.bar
else:
return c.spam
我想要一个高阶函数,它能够自省传递的函数,并通过点语法检索代码中提到的参数成员,具有以下行为:
>>> member_inspector(eggs, 'c')
('foo','spam')
>>> member_inspector(eggs, 'b')
('bar')
>>> member_inspector(eggs, 'a')
()
这能做到吗?怎么样?
这是一个基本版本:
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