AST Unparser for Python
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
- gotcha Python 3.9+ includes `ast.unparse` natively. The standalone `astunparse` library is primarily useful for projects targeting Python versions prior to 3.9 or when specific behaviors of this library are preferred over the built-in one. For newer Python versions, `ast.unparse` is generally the recommended approach.
- breaking While `astunparse` aims for broad compatibility (Python 2.6 through 3.8 as per its last update), the underlying Python AST structure can change significantly between major Python versions. For example, Python 3.12 introduced changes (PEP 695) to AST node attributes, which could affect code relying on specific AST node structures or the exact output for constructs like f-strings. This means strict round-trip compatibility across different Python versions cannot always be guaranteed by any AST unparser.
- gotcha `astunparse` (and the standard `ast` module it derives from) does not preserve or unparse PEP 484 type comments. If your project's code includes type annotations and you need them preserved after unparsing, `astunparse` will discard them.
Install
-
pip install astunparse
Imports
- unparse
import astunparse # ... astunparse.unparse(my_ast_node)
- dump
import astunparse # ... astunparse.dump(my_ast_node)
Quickstart
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)