An AST unparser for Python that converts Python AST objects back into readable source code
npx @tessl/cli install tessl/pypi-astunparse@1.6.00
# astunparse
1
2
An AST unparser for Python that converts Python Abstract Syntax Tree (AST) objects back into readable source code. This library provides both unparsing functionality to convert AST back to source code and pretty-printing functionality to display AST structure in a readable format.
3
4
## Package Information
5
6
- **Package Name**: astunparse
7
- **Language**: Python
8
- **Installation**: `pip install astunparse`
9
10
## Core Imports
11
12
```python
13
import astunparse
14
```
15
16
For advanced usage:
17
18
```python
19
from astunparse import Unparser, Printer
20
from astunparse import unparser
21
```
22
23
## Basic Usage
24
25
```python
26
import ast
27
import astunparse
28
import inspect
29
30
# Convert source code to AST and back to source
31
source = "x = 1 + 2"
32
tree = ast.parse(source)
33
unparsed = astunparse.unparse(tree)
34
print(unparsed) # Output: (1 + 2)
35
36
# Pretty-print AST structure
37
dump_output = astunparse.dump(tree)
38
print(dump_output)
39
40
# Roundtrip a Python file (parse and unparse)
41
astunparse.unparser.roundtrip("example.py")
42
43
# Get back source code from a function
44
tree = ast.parse(inspect.getsource(ast))
45
source_code = astunparse.unparse(tree)
46
```
47
48
## Capabilities
49
50
### AST Unparsing
51
52
Convert Python AST objects back into readable source code.
53
54
```python { .api }
55
def unparse(tree):
56
"""
57
Convert an AST tree back to Python source code.
58
59
Parameters:
60
- tree: AST object to unparse
61
62
Returns:
63
str: String containing the unparsed Python source code
64
"""
65
```
66
67
### AST Pretty-Printing
68
69
Display AST tree structure in a readable, formatted representation.
70
71
```python { .api }
72
def dump(tree):
73
"""
74
Pretty-print an AST tree structure in a readable format.
75
76
Parameters:
77
- tree: AST object to dump
78
79
Returns:
80
str: String containing pretty-printed AST structure
81
"""
82
```
83
84
### Advanced Unparsing Control
85
86
Direct control over the unparsing process with custom output destinations.
87
88
```python { .api }
89
class Unparser:
90
"""
91
Core class that recursively traverses AST and outputs source code.
92
Methods in this class recursively traverse an AST and output source code
93
for the abstract syntax; original formatting is disregarded.
94
"""
95
96
def __init__(self, tree, file=sys.stdout):
97
"""
98
Initialize Unparser and process the AST tree.
99
100
Parameters:
101
- tree: AST object to unparse
102
- file: Output file object (default: sys.stdout)
103
"""
104
105
def fill(self, text=""):
106
"""
107
Indent a piece of text according to the current indentation level.
108
109
Parameters:
110
- text: Text to indent (default: empty string)
111
"""
112
113
def write(self, text):
114
"""
115
Append a piece of text to the current line.
116
117
Parameters:
118
- text: Text to append
119
"""
120
121
def enter(self):
122
"""Print ':' and increase the indentation level."""
123
124
def leave(self):
125
"""Decrease indentation level."""
126
127
def dispatch(self, tree):
128
"""
129
Main method that handles AST node traversal.
130
131
Parameters:
132
- tree: AST node to dispatch
133
"""
134
```
135
136
### Advanced AST Structure Printing
137
138
Direct control over AST structure visualization with custom formatting.
139
140
```python { .api }
141
class Printer(ast.NodeVisitor):
142
"""
143
AST node visitor that pretty-prints AST structure with configurable formatting.
144
"""
145
146
def __init__(self, file=sys.stdout, indent=" "):
147
"""
148
Initialize Printer with output destination and indentation.
149
150
Parameters:
151
- file: Output file object (default: sys.stdout)
152
- indent: Indentation string (default: " ")
153
"""
154
155
def visit(self, node):
156
"""
157
Visit and print an AST node.
158
159
Parameters:
160
- node: AST node to visit and print
161
"""
162
163
def write(self, text):
164
"""
165
Write text to the output file.
166
167
Parameters:
168
- text: Text to write
169
"""
170
171
def generic_visit(self, node):
172
"""
173
Default node visiting behavior for AST nodes.
174
175
Parameters:
176
- node: AST node to visit with default behavior
177
"""
178
```
179
180
### File Roundtrip Processing
181
182
Process Python files by parsing to AST and unparsing back to source code. This function is available in the `unparser` module.
183
184
```python { .api }
185
# Access via: astunparse.unparser.roundtrip(filename, output)
186
def roundtrip(filename, output=sys.stdout):
187
"""
188
Read Python file, parse to AST, and unparse back to source code.
189
190
Parameters:
191
- filename: Path to Python file to roundtrip
192
- output: Output file object (default: sys.stdout)
193
"""
194
```
195
196
## Constants
197
198
```python { .api }
199
__version__ = "1.6.3"
200
```
201
202
## Types
203
204
```python { .api }
205
# Built-in types used
206
from typing import Any, Optional, TextIO
207
from ast import AST
208
209
# File-like objects for output
210
TextIO = typing.TextIO # For file parameter in classes
211
```
212
213
## Error Handling
214
215
The library handles:
216
- Large float and imaginary literals (converted to `INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1)`)
217
- Python 2/3 compatibility via six library
218
- File encoding detection for Python 3 via tokenize module
219
- AST traversal and node dispatch errors
220
221
## Dependencies
222
223
- `six`: Python 2/3 compatibility library
224
- `ast`: Python Abstract Syntax Tree module (standard library)
225
- `sys`: System-specific parameters and functions (standard library)
226
- `tokenize`: Tokenizer for Python source (standard library)
227
228
## Supported Python Versions
229
230
Python 2.6, 2.7, 3.5, 3.6, 3.7, 3.8 (supports single-source compatibility across versions)