ASTOR: Read/rewrite/write Python ASTs
astor is a Python library designed for easy manipulation of Python source code via its Abstract Syntax Tree (AST). It provides functionality to round-trip an AST back to Python source, pretty-print ASTs for debugging, and offers both recursive and non-recursive tree traversal mechanisms. It focuses on generating readable code from modified ASTs. The current version is 0.8.1, released in late 2019, and its release cadence is very slow, indicating a maintenance-only status.
Warnings
- breaking The `ast` module in Python frequently changes between minor versions (e.g., 3.8, 3.9, 3.10+). While `astor` 0.8.1 has some compatibility fixes for Python 3.8 features (like `ast.Constant` and assignment expressions), it is unlikely to fully support AST changes introduced in Python 3.9 and newer (e.g., `match/case` in 3.10, `type statement` in 3.12). Users on Python 3.9+ might encounter issues or incorrect code generation.
- deprecated Several functions and submodules have been deprecated since `astor` 0.6 and 0.8. The `astor.codegen` submodule, `astor.parsefile()`, and `astor.dump()` are officially deprecated.
- gotcha When using `astor.code_to_ast()` with decorated functions in Python 3.8.1, a `KeyError` could occur due to mismatches in line numbers in the internal cache. This issue was resolved in a commit that shipped with version 0.8.1.
- deprecated Python 3.12 (and later 3.x versions) deprecates old AST node types like `ast.Num`, `ast.Str`, `ast.Bytes`, `ast.NameConstant`, and `ast.Ellipsis` in favor of `ast.Constant`. Using `astor` on these newer Python versions may produce `DeprecationWarning`s or fail to handle ASTs correctly if it relies on these removed nodes.
Install
-
pip install astor
Imports
- astor
import astor
- to_source
from astor import to_source
- parse_file
from astor import parse_file
- dump_tree
from astor import dump_tree
- SourceGenerator
from astor import SourceGenerator
Quickstart
import ast
import astor
# Example Python code as a string
source_code = """
def greet(name):
message = f"Hello, {name}!"
return message
"""
# Parse the source code into an AST
tree = ast.parse(source_code)
# Convert the AST back to source code
generated_source = astor.to_source(tree)
print("Original code:\n" + source_code)
print("\nGenerated code from AST:\n" + generated_source)