astpretty
astpretty is a Python library designed to pretty-print the Abstract Syntax Tree (AST) generated by Python's standard library `ast.parse` function. It offers a more readable, indented, and detailed representation of AST nodes compared to the built-in `ast.dump`, making it useful for debugging and understanding code structure. The current version is 3.0.0, released in May 2022, requiring Python 3.8+. It's a stable, focused utility with infrequent but significant updates.
Warnings
- breaking Python 2 support was dropped with `astpretty` version 2.0.0. Version 3.0.0 further increased the minimum Python requirement to 3.8. Older Python 2 or early Python 3 projects will need to use an older `astpretty` version or upgrade their Python interpreter.
- gotcha `astpretty.pprint` provides a highly detailed, multi-line, indented output, including `lineno` and `col_offset` by default. This is significantly more verbose than the standard library's `ast.dump`, which outputs a single-line representation. Users accustomed to `ast.dump` might find `astpretty`'s default output overwhelming if they only need a compact string.
- gotcha `astpretty` operates on an existing AST node object, not directly on source code strings. You must first parse your code into an AST object using `ast.parse` from the Python standard library before passing it to `astpretty.pprint` or `astpretty.pformat`.
Install
-
pip install astpretty
Imports
- pprint
import astpretty astpretty.pprint(node)
- pformat
import astpretty result = astpretty.pformat(node)
Quickstart
import ast
import astpretty
code_snippet = """
def greet(name):
print(f'Hello, {name}!')
"""
# Parse the code into an AST node
parsed_ast = ast.parse(code_snippet)
# Pretty print the entire AST
astpretty.pprint(parsed_ast)
# Or pretty print a specific node, e.g., the function definition
# astpretty.pprint(parsed_ast.body[0], show_offsets=False, indent=' ') # Example with options