gpt4 book ai didi

python - 是否可以使用 ast.NodeVisitor 访问 Python AST 中的节点两次或更改遍历顺序?

转载 作者:行者123 更新时间:2023-11-28 19:59:14 33 4
gpt4 key购买 nike

NodeVisitor 以深度优先的方式遍历 AST,并且在进入时仅访问每个节点一次。因此,用它做一些严肃的事情是有问题的。是否可以更改其默认行为?

最佳答案

也许有人会对一些草拟的例子感兴趣,如何做 DSblizzard 提出的建议,所以听听我的例子:

import ast

class RecursiveVisitor(ast.NodeVisitor):
""" example recursive visitor """

def recursive(func):
""" decorator to make visitor work recursive """
def wrapper(self,node):
func(self,node)
for child in ast.iter_child_nodes(node):
self.visit(child)
return wrapper

@recursive
def visit_Assign(self,node):
""" visit a Assign node and visits it recursively"""
print(type(node).__name__)

@recursive
def visit_BinOp(self, node):
""" visit a BinOp node and visits it recursively"""
print(type(node).__name__)

@recursive
def visit_Call(self,node):
""" visit a Call node and visits it recursively"""
print(type(node).__name__)

@recursive
def visit_Lambda(self,node):
""" visit a Function node """
print(type(node).__name__)

@recursive
def visit_FunctionDef(self,node):
""" visit a Function node and visits it recursively"""
print(type(node).__name__)

@recursive
def visit_Module(self,node):
""" visit a Module node and the visits recursively"""
pass

def generic_visit(self,node):
pass

class SimpleVisitor(ast.NodeVisitor):
""" simple visitor for comparison """

def recursive(func):
""" decorator to make visitor work recursive """
def wrapper(self,node):
func(self,node)
for child in ast.iter_child_nodes(node):
self.visit(child)
return wrapper

def visit_Assign(self,node):
""" visit a Assign node """
print(type(node).__name__)

def visit_BinOp(self, node):
""" visit a BinOp node """
print(type(node).__name__)

def visit_Call(self,node):
""" visit a Call node """
print(type(node).__name__)

def visit_Lambda(self,node):
""" visit a Function node """
print(type(node).__name__)

def visit_FunctionDef(self,node):
""" visit a Function node """
print(type(node).__name__)

@recursive
def visit_Module(self,node):
""" visit a Module node and the visits recursively, otherwise you
wouldn't see anything here"""
pass

def generic_visit(self,node):
pass

# usage example
a = """
b= lambda x: x*5 +5
def hhh(u):
b=19
return u*b
m=hhh(9*4+5)
"""

recursive_visitor = RecursiveVisitor()
simple_visitor = SimpleVisitor()
tree = ast.parse(a)
print('\nvisit recursive\n')
recursive_visitor.visit(tree)
print('\nvisit simple\n')
simple_visitor.visit(tree)

希望有人会发现它有用。

关于python - 是否可以使用 ast.NodeVisitor 访问 Python AST 中的节点两次或更改遍历顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5533662/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com