示例工程 23-bytecode-dis-ast

23-bytecode-dis-ast/04-ast-transformer/README.md

markdown · 0.6 KB

# 04 · ast-transformer
 
**演示**:`ast.NodeTransformer` 把 `+` 改成 `-`,`ast.fix_missing_locations` 补位置,`compile` + `exec` 执行改写后的树。
**运行**:
 
```sh
uv run python examples/23-bytecode-dis-ast/04-ast-transformer/ast_transformer.py
```
 
**预期输出**(3.12.9):
 
```text
transformed: result = 10 - 3
result: 7
```
 
**依赖**:仅标准库。
**注意**:`exec` 只执行本文件内的固定字符串,不处理外部输入;生产里不要对不可信源码做 `compile`/`exec`。改写后必须 `fix_missing_locations`,否则编译可能报错。