or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-astunparse

An AST unparser for Python that converts Python AST objects back into readable source code

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/astunparse@1.6.x

To install, run

npx @tessl/cli install tessl/pypi-astunparse@1.6.0

index.mddocs/

astunparse

An 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.

Package Information

  • Package Name: astunparse
  • Language: Python
  • Installation: pip install astunparse

Core Imports

import astunparse

For advanced usage:

from astunparse import Unparser, Printer
from astunparse import unparser

Basic Usage

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

Capabilities

AST Unparsing

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
    """

AST Pretty-Printing

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
    """

Advanced Unparsing Control

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
        """

Advanced AST Structure Printing

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
        """

File Roundtrip Processing

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

Constants

__version__ = "1.6.3"

Types

# 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 classes

Error Handling

The library handles:

  • Large float and imaginary literals (converted to INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1))
  • Python 2/3 compatibility via six library
  • File encoding detection for Python 3 via tokenize module
  • AST traversal and node dispatch errors

Dependencies

  • six: Python 2/3 compatibility library
  • ast: Python Abstract Syntax Tree module (standard library)
  • sys: System-specific parameters and functions (standard library)
  • tokenize: Tokenizer for Python source (standard library)

Supported Python Versions

Python 2.6, 2.7, 3.5, 3.6, 3.7, 3.8 (supports single-source compatibility across versions)