An AST unparser for Python that converts Python AST objects back into readable source code
npx @tessl/cli install tessl/pypi-astunparse@1.6.0An AST unparser for Python that converts Python Abstract Syntax Tree (AST) objects back into readable source code. This library provides both unparsing functionality to convert AST back to source code and pretty-printing functionality to display AST structure in a readable format.
pip install astunparseimport astunparseFor advanced usage:
from astunparse import Unparser, Printer
from astunparse import unparserimport ast
import astunparse
import inspect
# Convert source code to AST and back to source
source = "x = 1 + 2"
tree = ast.parse(source)
unparsed = astunparse.unparse(tree)
print(unparsed) # Output: (1 + 2)
# Pretty-print AST structure
dump_output = astunparse.dump(tree)
print(dump_output)
# Roundtrip a Python file (parse and unparse)
astunparse.unparser.roundtrip("example.py")
# Get back source code from a function
tree = ast.parse(inspect.getsource(ast))
source_code = astunparse.unparse(tree)Convert Python AST objects back into readable source code.
def unparse(tree):
"""
Convert an AST tree back to Python source code.
Parameters:
- tree: AST object to unparse
Returns:
str: String containing the unparsed Python source code
"""Display AST tree structure in a readable, formatted representation.
def dump(tree):
"""
Pretty-print an AST tree structure in a readable format.
Parameters:
- tree: AST object to dump
Returns:
str: String containing pretty-printed AST structure
"""Direct control over the unparsing process with custom output destinations.
class Unparser:
"""
Core class that recursively traverses AST and outputs source code.
Methods in this class recursively traverse an AST and output source code
for the abstract syntax; original formatting is disregarded.
"""
def __init__(self, tree, file=sys.stdout):
"""
Initialize Unparser and process the AST tree.
Parameters:
- tree: AST object to unparse
- file: Output file object (default: sys.stdout)
"""
def fill(self, text=""):
"""
Indent a piece of text according to the current indentation level.
Parameters:
- text: Text to indent (default: empty string)
"""
def write(self, text):
"""
Append a piece of text to the current line.
Parameters:
- text: Text to append
"""
def enter(self):
"""Print ':' and increase the indentation level."""
def leave(self):
"""Decrease indentation level."""
def dispatch(self, tree):
"""
Main method that handles AST node traversal.
Parameters:
- tree: AST node to dispatch
"""Direct control over AST structure visualization with custom formatting.
class Printer(ast.NodeVisitor):
"""
AST node visitor that pretty-prints AST structure with configurable formatting.
"""
def __init__(self, file=sys.stdout, indent=" "):
"""
Initialize Printer with output destination and indentation.
Parameters:
- file: Output file object (default: sys.stdout)
- indent: Indentation string (default: " ")
"""
def visit(self, node):
"""
Visit and print an AST node.
Parameters:
- node: AST node to visit and print
"""
def write(self, text):
"""
Write text to the output file.
Parameters:
- text: Text to write
"""
def generic_visit(self, node):
"""
Default node visiting behavior for AST nodes.
Parameters:
- node: AST node to visit with default behavior
"""Process Python files by parsing to AST and unparsing back to source code. This function is available in the unparser module.
# Access via: astunparse.unparser.roundtrip(filename, output)
def roundtrip(filename, output=sys.stdout):
"""
Read Python file, parse to AST, and unparse back to source code.
Parameters:
- filename: Path to Python file to roundtrip
- output: Output file object (default: sys.stdout)
"""__version__ = "1.6.3"# Built-in types used
from typing import Any, Optional, TextIO
from ast import AST
# File-like objects for output
TextIO = typing.TextIO # For file parameter in classesThe library handles:
INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1))six: Python 2/3 compatibility libraryast: Python Abstract Syntax Tree module (standard library)sys: System-specific parameters and functions (standard library)tokenize: Tokenizer for Python source (standard library)Python 2.6, 2.7, 3.5, 3.6, 3.7, 3.8 (supports single-source compatibility across versions)