CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-astor

Read/rewrite/write Python ASTs

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

ast-to-source.mddocs/

AST to Source Conversion

Core functionality for converting Python AST nodes back to readable source code. This module provides the primary interface for transforming abstract syntax trees into executable Python code with customizable formatting and output options.

Capabilities

Source Generation

Converts an AST node tree back into Python source code with comprehensive formatting control.

def to_source(node, indent_with=' ' * 4, add_line_information=False, 
              pretty_string=pretty_string, pretty_source=pretty_source, 
              source_generator_class=None):
    """
    Convert an AST node tree back into Python source code.
    
    Parameters:
    - node: AST node to convert
    - indent_with: str, string used for indentation (default: 4 spaces)
    - add_line_information: bool, whether to add line number comments (default: False)
    - pretty_string: function, function for string prettification
    - pretty_source: function, function for source prettification  
    - source_generator_class: class, custom SourceGenerator class (default: SourceGenerator)
    
    Returns:
    str: String representation of the Python source code
    """

Usage Example:

import ast
import astor

# Parse some code
code = "def add(a, b): return a + b"
tree = ast.parse(code)

# Convert back to source with default formatting
source = astor.to_source(tree)
print(source)

# Convert with custom indentation
source_tabs = astor.to_source(tree, indent_with='\t')
print(source_tabs)

# Add line information for debugging
source_with_lines = astor.to_source(tree, add_line_information=True)
print(source_with_lines)

Source Generator Class

The core AST visitor that performs the actual transformation from AST nodes to source code. This class can be customized for specialized source generation needs.

class SourceGenerator(ExplicitNodeVisitor):
    """
    AST visitor that transforms syntax tree into Python source code.
    
    Inherits from ExplicitNodeVisitor to ensure all node types are handled explicitly.
    """
    
    def __init__(self, indent_with, add_line_information=False, pretty_string=pretty_string):
        """
        Initialize the source generator.
        
        Parameters:
        - indent_with: str, string to use for indentation
        - add_line_information: bool, whether to add line number comments
        - pretty_string: function, string prettification function
        """
    
    def visit(self, node):
        """
        Visit and convert an AST node.
        
        Parameters:
        - node: AST node to visit
        
        Returns:
        Result of node-specific visit method
        """
    
    def write(self, *params):
        """
        Write parameters to result.
        
        Parameters:
        - *params: Parameters to write to output
        """
    
    def newline(self, node=None, extra=0):
        """
        Add newlines to output.
        
        Parameters:
        - node: AST node (optional)
        - extra: int, number of extra newlines to add
        """
    
    def body(self, statements):
        """
        Process body statements with proper indentation.
        
        Parameters:
        - statements: list, AST statement nodes to process
        """

Advanced Usage:

import ast
import astor

# Create custom source generator for specialized formatting
class CustomSourceGenerator(astor.SourceGenerator):
    def visit_FunctionDef(self, node):
        # Custom function definition formatting
        self.write("function ", node.name, "(")
        # ... custom logic
        
# Use custom generator
code = "def hello(): pass"
tree = ast.parse(code)
custom_source = astor.to_source(tree, source_generator_class=CustomSourceGenerator)

Delimiter Context Manager

Context manager for adding delimiters around SourceGenerator output.

class Delimit:
    """Context manager for adding delimiters around SourceGenerator output."""
    
    def __init__(self, tree, *args):
        """
        Initialize with tree and delimiter arguments.
        
        Parameters:
        - tree: SourceGenerator instance
        - *args: Delimiter arguments
        """
    
    def __enter__(self):
        """Enter context manager."""
    
    def __exit__(self, *args):
        """Exit context manager."""

String Formatting Utilities

Pretty String Formatting

Advanced string representation for decompiler output, choosing between standard repr() and triple-quoted strings based on context.

def pretty_string(s, embedded, current_line, uni_lit=False, min_trip_str=20, max_line=100):
    """
    Format strings for decompiler, choosing between repr() and triple-quoted strings.
    
    Parameters:
    - s: str, string to format
    - embedded: bool, whether string is embedded in larger expression
    - current_line: int, current line position
    - uni_lit: bool, whether to use unicode literals (default: False)
    - min_trip_str: int, minimum length for triple-quoted strings (default: 20)
    - max_line: int, maximum line length (default: 100)
    
    Returns:
    str: Formatted string representation
    """

Source Prettification

Post-processing function to prettify generated source code for improved readability.

def pretty_source(source):
    """
    Post-process and prettify generated source code.
    
    Parameters:
    - source: str, source code to prettify
    
    Returns:
    str: Prettified source string
    """

Usage Example:

import ast
import astor

# Generate source with custom prettification
def custom_prettify(source):
    # Add custom formatting rules
    return source.replace(";", ";\n")

code = "a = 1; b = 2; c = 3"
tree = ast.parse(code)
pretty_source = astor.to_source(tree, pretty_source=custom_prettify)
print(pretty_source)

Install with Tessl CLI

npx tessl i tessl/pypi-astor

docs

ast-to-source.md

file-operations.md

index.md

operator-utilities.md

tree-manipulation.md

tile.json