Read/rewrite/write Python ASTs
npx @tessl/cli install tessl/pypi-astor@0.8.0A Python library for reading, rewriting, and writing Python Abstract Syntax Trees (ASTs). Astor enables programmatic manipulation of Python source code through AST transformations, providing round-trip conversion between source code and AST representations while preserving code readability.
pip install astorimport astorMost commonly used functions:
from astor import to_source, parse_file, dump_treeimport ast
import astor
# Parse Python source code into an AST
source_code = """
def hello(name):
print(f"Hello, {name}!")
return name.upper()
"""
# Parse source to AST
tree = ast.parse(source_code)
# Convert AST back to source code
generated_source = astor.to_source(tree)
print(generated_source)
# Parse a file directly
tree = astor.parse_file('example.py')
# Pretty-print AST structure for debugging
print(astor.dump_tree(tree))Astor provides a comprehensive AST manipulation framework with several key components:
The library is designed for maximum utility in code generation tools, static analysis frameworks, refactoring utilities, and any application requiring programmatic Python code manipulation.
Core functionality for converting Python AST nodes back to readable source code with customizable formatting options and pretty-printing capabilities.
def to_source(node, indent_with=' ' * 4, add_line_information=False,
pretty_string=pretty_string, pretty_source=pretty_source,
source_generator_class=None):
"""Convert AST node tree to Python source code."""Tools for walking, inspecting, dumping, and modifying AST structures. Includes utilities for tree traversal, node comparison, and AST pretty-printing.
def dump_tree(node, name=None, initial_indent='', indentation=' ',
maxline=120, maxmerged=80):
"""Dump AST in pretty-printed format with indentation."""
def iter_node(node, name='', unknown=None):
"""Iterate over AST node attributes or list items."""
def strip_tree(node):
"""Strip AST by removing all attributes not in _fields."""High-level interfaces for parsing Python files into ASTs and managing code objects with caching support.
def parse_file(fname):
"""Parse Python file into AST."""
class CodeToAst:
"""Convert modules/functions to AST with caching support."""Utilities for working with Python operators, including symbol extraction and precedence handling for proper expression formatting.
def get_op_symbol(obj, fmt='%s'):
"""Return symbol string for AST operator node."""
def get_op_precedence(obj):
"""Return precedence value for AST operator node."""__version__: str = "0.8.1"