Syntax-highlighting, declarative and composable pretty printer for Python 3.5+
npx @tessl/cli install tessl/pypi-prettyprinter@0.18.00
# PrettyPrinter
1
2
A syntax-highlighting, declarative and composable pretty printer for Python 3.5+ that serves as a powerful drop-in replacement for the standard library's pprint module. PrettyPrinter implements a modified Wadler-Leijen layout algorithm for optimal text formatting and includes extensive customization capabilities, syntax highlighting, and a plugin system for third-party library support.
3
4
## Package Information
5
6
- **Package Name**: prettyprinter
7
- **Language**: Python
8
- **Installation**: `pip install prettyprinter`
9
- **Dependencies**: colorful>=0.4.0, Pygments>=2.2.0
10
11
## Core Imports
12
13
```python
14
import prettyprinter
15
```
16
17
Common usage patterns:
18
19
```python
20
from prettyprinter import pprint, cpprint, pformat, register_pretty
21
```
22
23
For custom pretty printers:
24
25
```python
26
from prettyprinter import (
27
register_pretty, pretty_call, comment, python_to_sdocs,
28
default_render_to_stream
29
)
30
```
31
32
For document system functions:
33
34
```python
35
from prettyprinter.doc import (
36
concat, group, nest, annotate, contextual, always_break,
37
flat_choice, align, hang, fill
38
)
39
```
40
41
## Basic Usage
42
43
```python
44
import prettyprinter
45
from prettyprinter import pprint, cpprint
46
47
# Basic data structures
48
data = {
49
'users': [
50
{'name': 'Alice', 'age': 30, 'scores': [95, 87, 92]},
51
{'name': 'Bob', 'age': 25, 'scores': [88, 91, 85]}
52
],
53
'settings': {'debug': True, 'max_connections': 100}
54
}
55
56
# Pretty print without color
57
pprint(data, width=60)
58
59
# Pretty print with syntax highlighting
60
cpprint(data, width=60, style='light')
61
62
# Get formatted string
63
formatted = prettyprinter.pformat(data, width=40)
64
print(formatted)
65
66
# Install extras for third-party library support
67
prettyprinter.install_extras(['numpy', 'requests', 'dataclasses'])
68
```
69
70
## Architecture
71
72
PrettyPrinter is built around a flexible document-based layout system:
73
74
- **Document System**: Abstract representation of formatted output using composable document primitives
75
- **Layout Algorithm**: Modified Wadler-Leijen algorithm that optimally fits content within width constraints
76
- **Registration System**: Extensible pretty printer registration for custom types using singledispatch
77
- **Context System**: Immutable context objects that track formatting state during document construction
78
- **Rendering System**: Separate renderers for plain text and syntax-highlighted output
79
- **Extras System**: Plugin architecture for third-party library integration
80
81
This design enables declarative pretty printing where users focus on describing the desired output structure rather than managing layout details, while providing extensive customization capabilities for advanced use cases.
82
83
## Capabilities
84
85
### Core Pretty Printing
86
87
Primary functions for pretty printing Python objects with configurable formatting options, including both plain text and syntax-highlighted output.
88
89
```python { .api }
90
def pprint(object, stream=None, indent=4, width=79, depth=None, *,
91
compact=False, ribbon_width=71, max_seq_len=1000,
92
sort_dict_keys=False, end='\n'): ...
93
94
def cpprint(object, stream=None, indent=4, width=79, depth=None, *,
95
compact=False, ribbon_width=71, max_seq_len=1000,
96
sort_dict_keys=False, style=None, end='\n'): ...
97
98
def pformat(object, indent=4, width=79, depth=None, *,
99
ribbon_width=71, max_seq_len=1000, compact=False,
100
sort_dict_keys=False) -> str: ...
101
102
def pretty_repr(instance) -> str: ...
103
104
def python_to_sdocs(value, indent, width, depth, ribbon_width,
105
max_seq_len, sort_dict_keys): ...
106
107
def default_render_to_stream(stream, sdocs, newline='\n', separator=' '): ...
108
```
109
110
[Core Pretty Printing](./core-printing.md)
111
112
### Pretty Printer Registration
113
114
System for registering custom pretty printers for user-defined types and creating formatted function call representations.
115
116
```python { .api }
117
def register_pretty(type=None, predicate=None): ...
118
119
def pretty_call(ctx, fn, *args, **kwargs): ...
120
121
def pretty_call_alt(ctx, fn, args=(), kwargs=()): ...
122
123
def is_registered(type, *, check_superclasses=False, check_deferred=True,
124
register_deferred=True) -> bool: ...
125
```
126
127
[Pretty Printer Registration](./registration.md)
128
129
### Configuration Management
130
131
Functions for managing global configuration settings and styling options for pretty printing output.
132
133
```python { .api }
134
def set_default_config(*, style=None, max_seq_len=None, width=None,
135
ribbon_width=None, depth=None, sort_dict_keys=None): ...
136
137
def get_default_config(): ...
138
139
def set_default_style(style): ...
140
```
141
142
[Configuration Management](./configuration.md)
143
144
### Document System
145
146
Low-level document creation and manipulation functions for building custom layout algorithms and pretty printers.
147
148
```python { .api }
149
def concat(docs): ...
150
def group(doc): ...
151
def nest(i, doc): ...
152
def annotate(annotation, doc): ...
153
def contextual(fn): ...
154
def always_break(doc): ...
155
def flat_choice(when_broken, when_flat): ...
156
def align(doc): ...
157
def hang(i, doc): ...
158
def fill(docs): ...
159
```
160
161
[Document System](./document-system.md)
162
163
### Comments and Annotations
164
165
Functions for adding comments and annotations to pretty printed output.
166
167
```python { .api }
168
def comment(value, comment_text): ...
169
def trailing_comment(value, comment_text): ...
170
```
171
172
[Comments and Annotations](./comments.md)
173
174
### Extras and Extensions
175
176
System for installing and managing third-party library integrations and extensions.
177
178
```python { .api }
179
def install_extras(include=ALL_EXTRAS, *, exclude=frozenset(),
180
raise_on_error=False, warn_on_error=True): ...
181
182
ALL_EXTRAS: frozenset
183
```
184
185
[Extras and Extensions](./extras.md)
186
187
## Types
188
189
```python { .api }
190
class PrettyPrinter:
191
"""Pretty printer class providing pprint-compatible interface."""
192
def __init__(self, *args, **kwargs): ...
193
def pprint(self, object): ...
194
def pformat(self, object) -> str: ...
195
def isrecursive(self, object) -> bool: ...
196
def isreadable(self, object) -> bool: ...
197
def format(self, object): ...
198
199
class PrettyContext:
200
"""Immutable context object used during pretty printer execution."""
201
def __init__(self, indent, depth_left, visited=None,
202
multiline_strategy='MULTILINE_STRATEGY_PLAIN',
203
max_seq_len=1000, sort_dict_keys=False, user_ctx=None): ...
204
def assoc(self, key, value): ...
205
def get(self, key, default=None): ...
206
def nested_call(): ...
207
def start_visit(self, value): ...
208
def end_visit(self, value): ...
209
def is_visited(self, value) -> bool: ...
210
211
class Doc:
212
"""Base class for document types in the layout system."""
213
def normalize(self): ...
214
215
class Concat(Doc):
216
"""Document representing concatenation of multiple documents."""
217
def __init__(self, docs): ...
218
219
class Group(Doc):
220
"""Document that attempts single-line layout when possible."""
221
def __init__(self, doc): ...
222
223
class Nest(Doc):
224
"""Document with increased indentation level."""
225
def __init__(self, indent, doc): ...
226
227
class Annotated(Doc):
228
"""Document with annotation metadata."""
229
def __init__(self, doc, annotation): ...
230
231
class FlatChoice(Doc):
232
"""Document with conditional layout options."""
233
def __init__(self, when_broken, when_flat, normalize_on_access=False): ...
234
```