ast Parses And Rewrites Python Source

Parse Python source with ast, insert a trace call with NodeTransformer, and unparse the rewritten tree back to valid source.

PythonData Integrity

Code

pythonsnippet
40 lines
import ast


SOURCE = '''
def area(width, height):
    return width * height

print(area(3, 4))
'''


class AddTrace(ast.NodeTransformer):
    def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef:
        # 在函数体开头插入 print(node.name),记录被调用的函数
        call = ast.Call(
            func=ast.Name(id='print', ctx=ast.Load()),
            args=[ast.Constant(value=node.name)],
            keywords=[],
        )
        node.body.insert(0, ast.Expr(value=call))
        return node


def main() -> None:
    tree = ast.parse(SOURCE)
    print('top-level nodes:', [type(node).__name__ for node in tree.body])

    rewritten = AddTrace().visit(tree)
    ast.fix_missing_locations(rewritten)

    # compile 只验证树能生成代码,不在这里执行
    code = compile(rewritten, '<ast-demo>', 'exec')
    print('compiled constants:', code.co_consts[:2])

    print('rewritten source:')
    print(ast.unparse(rewritten))


if __name__ == '__main__':
    main()

How the snippet works

ast Parses And Rewrites Python Source reduces to the class AddTrace and the functions area, visit_FunctionDef and main.

Watch out for

  • Plan for an install step: ast is a real dependency, resolved by the package manager.

Applying it

Entry signature: def area(width, height)

The demo output is labeled (top-level nodes:, compiled constants:, rewritten source:); each label names the call that printed it.

Statements that matter

def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef:
    # 在函数体开头插入 print(node.name),记录被调用的函数
    call = ast.Call(
        func=ast.Name(id='print', ctx=ast.Load()),
        args=[ast.Constant(value=node.name)],
        keywords=[],
    )
    node.body.insert(0, ast.Expr(value=call))
    return node
def area(width, height):
    return width * height

Interactive Tools for This Topic

FAQ

Does this require external packages?
Yes — `ast`. Add it to your project before running the snippet.