[英]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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.