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.
pip install astunparseVerified import paths — ran on the pinned version, not inferred.
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.
For Python 3.9 and newer, prefer `ast.unparse(node)` directly. For older versions or specific `astunparse` features, continue using the library.
Test your unparsing logic thoroughly against target Python versions. When targeting newer Python versions, consider if the built-in `ast.unparse` might be more up-to-date with recent AST changes than the standalone library.
For use cases requiring the preservation of type comments, consider alternative libraries like `typed-astunparse`, which are built to work with `typed-ast` (an AST variant that includes type comment nodes).