Back to snippets

python_ast_nodevisitor_quickstart_for_strings_and_variables.py

python

A node visitor base class that walks the abstract syntax tree and calls a visito

15d ago15 linesdocs.python.org
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)
python_ast_nodevisitor_quickstart_for_strings_and_variables.py - Raysurfer Public Snippets