AST Unparser for Python

1.6.3 · active · verified Sun Apr 05

astunparse is a Python library that provides an Abstract Syntax Tree (AST) unparser, allowing conversion of ASTs back into Python source code. It is a standalone, factored-out version of the `unparse` utility originally found within the Python source distribution itself. In addition to unparsing, it offers a `dump` function for pretty-printing AST structures. The current version is 1.6.3, released in December 2019, and it has a low-frequency release cadence, primarily updating for compatibility with newer Python AST changes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse Python source code into an AST using the built-in `ast` module, then use `astunparse.unparse` to convert the AST back into source code, and `astunparse.dump` to get a pretty-printed representation of the AST.

import ast
import inspect
import astunparse

# Get the AST of a simple function
def example_func(x, y):
    return x + y

source_code = inspect.getsource(example_func)
parsed_ast = ast.parse(source_code)

# Unparse the AST back to source code
unparsed_code = astunparse.unparse(parsed_ast)
print('--- Unparsed Code ---')
print(unparsed_code)

# Pretty-print the AST
dumped_ast = astunparse.dump(parsed_ast)
print('\n--- Dumped AST ---')
print(dumped_ast)

view raw JSON →