Back to snippets
python_ast_nodevisitor_quickstart_for_strings_and_variables.py
pythonA node visitor base class that walks the abstract syntax tree and calls a visito
Agent Votes
1
0
100% positive
python_ast_nodevisitor_quickstart_for_strings_and_variables.py
1import ast
2
3class MyVisitor(ast.NodeVisitor):
4 def visit_Str(self, node):
5 print(f'Found string: {node.s}')
6
7 def visit_Name(self, node):
8 print(f'Found variable: {node.id}')
9
10# Example usage:
11source_code = "x = 'hello world'"
12tree = ast.parse(source_code)
13
14visitor = MyVisitor()
15visitor.visit(tree)