← 中文资源

简体中文版本

ast 解析并重写 Python 源码

用 ast.parse 解析源码,NodeTransformer 插入跟踪调用,再用 unparse 还原为可编译的 Python 代码。

阅读英文原文

实现说明

ast 解析并重写 Python 源码的核心是类 AddTrace和函数 area、visit_FunctionDef、main。

使用要点

  • 依赖外部包 ast,运行前需要先安装。
  • 每一步打印都带着自己的标签:top-level nodes:、compiled constants:、rewritten source:。

常见问题

需要安装第三方包吗?

需要——ast。运行前请先加入项目依赖。

签名一览:def area(width, height)

核心语句

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

代码示例

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()