Python ast: 判断 FunctionDef 是否在 ClassDef 中
Python ast: decide whether a FunctionDef is inside a ClassDef or not
我想从 Python 源代码构建一个 ast,然后从 ast 中获取特定信息。我遇到了以下问题:虽然遍历 ClassDef 的主体是可行的,但我如何确定方法是否在 class 内。
我构建的代码来自:
class A:
def foo(self):
pass
def foo(self):
pass
在这个例子中,我将点击所有 foo
s 但我无法判断它是否来自 class 或不是(因为它们具有相同的参数集,命名错误,但可以解释代码)。
def build_ast(self):
with open(self.path, 'r', encoding='utf-8') as fp:
tree = ast.parse(fp.read())
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
print(ast.dump(node))
# access the parent if it has
我对我的最终解决方案并不完全满意,但显然它适用于 Python 3.8.3:
根据我的经验,ast.walk
在 FunctionsDef 节点之前遍历 ClassDef 节点。
def build_ast(self):
with open(self.path, 'r', encoding='utf-8') as fp:
tree = ast.parse(fp.read())
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
if hasattr(node, "parent"):
print(node.parent.name, node.name)
else:
print(node.name, "is not in a class.")
if isinstance(node, ast.ClassDef):
for child in node.body:
if isinstance(child, ast.FunctionDef):
child.parent = node
我想从 Python 源代码构建一个 ast,然后从 ast 中获取特定信息。我遇到了以下问题:虽然遍历 ClassDef 的主体是可行的,但我如何确定方法是否在 class 内。
我构建的代码来自:
class A:
def foo(self):
pass
def foo(self):
pass
在这个例子中,我将点击所有 foo
s 但我无法判断它是否来自 class 或不是(因为它们具有相同的参数集,命名错误,但可以解释代码)。
def build_ast(self):
with open(self.path, 'r', encoding='utf-8') as fp:
tree = ast.parse(fp.read())
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
print(ast.dump(node))
# access the parent if it has
我对我的最终解决方案并不完全满意,但显然它适用于 Python 3.8.3:
根据我的经验,ast.walk
在 FunctionsDef 节点之前遍历 ClassDef 节点。
def build_ast(self):
with open(self.path, 'r', encoding='utf-8') as fp:
tree = ast.parse(fp.read())
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
if hasattr(node, "parent"):
print(node.parent.name, node.name)
else:
print(node.name, "is not in a class.")
if isinstance(node, ast.ClassDef):
for child in node.body:
if isinstance(child, ast.FunctionDef):
child.parent = node