0
# AST to Source Conversion
1
2
Core functionality for converting Python AST nodes back to readable source code. This module provides the primary interface for transforming abstract syntax trees into executable Python code with customizable formatting and output options.
3
4
## Capabilities
5
6
### Source Generation
7
8
Converts an AST node tree back into Python source code with comprehensive formatting control.
9
10
```python { .api }
11
def to_source(node, indent_with=' ' * 4, add_line_information=False,
12
pretty_string=pretty_string, pretty_source=pretty_source,
13
source_generator_class=None):
14
"""
15
Convert an AST node tree back into Python source code.
16
17
Parameters:
18
- node: AST node to convert
19
- indent_with: str, string used for indentation (default: 4 spaces)
20
- add_line_information: bool, whether to add line number comments (default: False)
21
- pretty_string: function, function for string prettification
22
- pretty_source: function, function for source prettification
23
- source_generator_class: class, custom SourceGenerator class (default: SourceGenerator)
24
25
Returns:
26
str: String representation of the Python source code
27
"""
28
```
29
30
**Usage Example:**
31
32
```python
33
import ast
34
import astor
35
36
# Parse some code
37
code = "def add(a, b): return a + b"
38
tree = ast.parse(code)
39
40
# Convert back to source with default formatting
41
source = astor.to_source(tree)
42
print(source)
43
44
# Convert with custom indentation
45
source_tabs = astor.to_source(tree, indent_with='\t')
46
print(source_tabs)
47
48
# Add line information for debugging
49
source_with_lines = astor.to_source(tree, add_line_information=True)
50
print(source_with_lines)
51
```
52
53
### Source Generator Class
54
55
The core AST visitor that performs the actual transformation from AST nodes to source code. This class can be customized for specialized source generation needs.
56
57
```python { .api }
58
class SourceGenerator(ExplicitNodeVisitor):
59
"""
60
AST visitor that transforms syntax tree into Python source code.
61
62
Inherits from ExplicitNodeVisitor to ensure all node types are handled explicitly.
63
"""
64
65
def __init__(self, indent_with, add_line_information=False, pretty_string=pretty_string):
66
"""
67
Initialize the source generator.
68
69
Parameters:
70
- indent_with: str, string to use for indentation
71
- add_line_information: bool, whether to add line number comments
72
- pretty_string: function, string prettification function
73
"""
74
75
def visit(self, node):
76
"""
77
Visit and convert an AST node.
78
79
Parameters:
80
- node: AST node to visit
81
82
Returns:
83
Result of node-specific visit method
84
"""
85
86
def write(self, *params):
87
"""
88
Write parameters to result.
89
90
Parameters:
91
- *params: Parameters to write to output
92
"""
93
94
def newline(self, node=None, extra=0):
95
"""
96
Add newlines to output.
97
98
Parameters:
99
- node: AST node (optional)
100
- extra: int, number of extra newlines to add
101
"""
102
103
def body(self, statements):
104
"""
105
Process body statements with proper indentation.
106
107
Parameters:
108
- statements: list, AST statement nodes to process
109
"""
110
```
111
112
**Advanced Usage:**
113
114
```python
115
import ast
116
import astor
117
118
# Create custom source generator for specialized formatting
119
class CustomSourceGenerator(astor.SourceGenerator):
120
def visit_FunctionDef(self, node):
121
# Custom function definition formatting
122
self.write("function ", node.name, "(")
123
# ... custom logic
124
125
# Use custom generator
126
code = "def hello(): pass"
127
tree = ast.parse(code)
128
custom_source = astor.to_source(tree, source_generator_class=CustomSourceGenerator)
129
```
130
131
### Delimiter Context Manager
132
133
Context manager for adding delimiters around SourceGenerator output.
134
135
```python { .api }
136
class Delimit:
137
"""Context manager for adding delimiters around SourceGenerator output."""
138
139
def __init__(self, tree, *args):
140
"""
141
Initialize with tree and delimiter arguments.
142
143
Parameters:
144
- tree: SourceGenerator instance
145
- *args: Delimiter arguments
146
"""
147
148
def __enter__(self):
149
"""Enter context manager."""
150
151
def __exit__(self, *args):
152
"""Exit context manager."""
153
```
154
155
## String Formatting Utilities
156
157
### Pretty String Formatting
158
159
Advanced string representation for decompiler output, choosing between standard repr() and triple-quoted strings based on context.
160
161
```python { .api }
162
def pretty_string(s, embedded, current_line, uni_lit=False, min_trip_str=20, max_line=100):
163
"""
164
Format strings for decompiler, choosing between repr() and triple-quoted strings.
165
166
Parameters:
167
- s: str, string to format
168
- embedded: bool, whether string is embedded in larger expression
169
- current_line: int, current line position
170
- uni_lit: bool, whether to use unicode literals (default: False)
171
- min_trip_str: int, minimum length for triple-quoted strings (default: 20)
172
- max_line: int, maximum line length (default: 100)
173
174
Returns:
175
str: Formatted string representation
176
"""
177
```
178
179
### Source Prettification
180
181
Post-processing function to prettify generated source code for improved readability.
182
183
```python { .api }
184
def pretty_source(source):
185
"""
186
Post-process and prettify generated source code.
187
188
Parameters:
189
- source: str, source code to prettify
190
191
Returns:
192
str: Prettified source string
193
"""
194
```
195
196
**Usage Example:**
197
198
```python
199
import ast
200
import astor
201
202
# Generate source with custom prettification
203
def custom_prettify(source):
204
# Add custom formatting rules
205
return source.replace(";", ";\n")
206
207
code = "a = 1; b = 2; c = 3"
208
tree = ast.parse(code)
209
pretty_source = astor.to_source(tree, pretty_source=custom_prettify)
210
print(pretty_source)
211
```