0
# Core Pretty Printing
1
2
Primary functions for pretty printing Python objects with comprehensive formatting options. These functions provide both plain text and syntax-highlighted output with extensive customization capabilities.
3
4
## Capabilities
5
6
### Plain Text Pretty Printing
7
8
Pretty print Python objects to a stream or string without syntax highlighting, providing optimal layout within specified width constraints.
9
10
```python { .api }
11
def pprint(object, stream=None, indent=4, width=79, depth=None, *,
12
compact=False, ribbon_width=71, max_seq_len=1000,
13
sort_dict_keys=False, end='\n'):
14
"""
15
Pretty print a Python value to stream (defaults to sys.stdout).
16
17
Parameters:
18
- object: The Python value to pretty print
19
- stream: Output stream (defaults to sys.stdout)
20
- indent (int): Number of spaces to add for each nesting level (default: 4)
21
- width (int): Soft maximum columns in output (default: 79)
22
- depth (int): Maximum depth to print nested structures (default: None)
23
- compact (bool): More compact output (default: False)
24
- ribbon_width (int): Soft maximum columns after indenting (default: 71)
25
- max_seq_len (int): Maximum sequence length before truncation (default: 1000)
26
- sort_dict_keys (bool): Sort dictionary keys in output (default: False)
27
- end (str): String appended after printing (default: '\n')
28
"""
29
```
30
31
### Colored Pretty Printing
32
33
Pretty print Python objects with syntax highlighting and color support using Pygments for enhanced readability.
34
35
```python { .api }
36
def cpprint(object, stream=None, indent=4, width=79, depth=None, *,
37
compact=False, ribbon_width=71, max_seq_len=1000,
38
sort_dict_keys=False, style=None, end='\n'):
39
"""
40
Pretty print a Python value with color and syntax highlighting.
41
42
Parameters:
43
- object: The Python value to pretty print
44
- stream: Output stream (defaults to sys.stdout)
45
- indent (int): Number of spaces per nesting level (default: 4)
46
- width (int): Soft maximum columns in output (default: 79)
47
- depth (int): Maximum depth for nested structures (default: None)
48
- compact (bool): More compact output (default: False)
49
- ribbon_width (int): Soft maximum columns after indenting (default: 71)
50
- max_seq_len (int): Maximum sequence length before truncation (default: 1000)
51
- sort_dict_keys (bool): Sort dictionary keys in output (default: False)
52
- style: Color style ('light', 'dark', or Style subclass) (default: auto-detected)
53
- end (str): String appended after printing (default: '\n')
54
"""
55
```
56
57
### String Formatting
58
59
Format Python objects as pretty printed strings without outputting to a stream, useful for capturing formatted output.
60
61
```python { .api }
62
def pformat(object, indent=4, width=79, depth=None, *,
63
ribbon_width=71, max_seq_len=1000, compact=None,
64
sort_dict_keys=False) -> str:
65
"""
66
Return pretty printed representation of object as a string.
67
68
Parameters:
69
- object: The Python value to format
70
- indent (int): Number of spaces per nesting level (default: 4)
71
- width (int): Soft maximum columns in output (default: 79)
72
- depth (int): Maximum depth for nested structures (default: None)
73
- ribbon_width (int): Soft maximum columns after indenting (default: 71)
74
- max_seq_len (int): Maximum sequence length before truncation (default: 1000)
75
- compact: Compatibility parameter (unused)
76
- sort_dict_keys (bool): Sort dictionary keys in output (default: False)
77
78
Returns:
79
- str: Pretty printed representation without color
80
"""
81
```
82
83
### Custom Repr Integration
84
85
Function for integrating prettyprinter with custom `__repr__` methods, enabling classes to use prettyprinter for their string representation.
86
87
```python { .api }
88
def pretty_repr(instance) -> str:
89
"""
90
Function assignable to __repr__ method to use prettyprinter for repr output.
91
92
Usage:
93
class MyClass:
94
__repr__ = pretty_repr
95
96
Parameters:
97
- instance: The instance being represented
98
99
Returns:
100
- str: Pretty printed representation of the instance
101
102
Raises:
103
- UserWarning: If no pretty printer is registered for the type
104
"""
105
```
106
107
### PrettyPrinter Class
108
109
Class providing a pprint-compatible interface with configurable options, useful for maintaining consistent formatting settings across multiple print operations.
110
111
```python { .api }
112
class PrettyPrinter:
113
"""
114
Pretty printer class with pprint-compatible interface.
115
116
Provides methods similar to pprint.PrettyPrinter but using
117
prettyprinter's enhanced formatting capabilities.
118
"""
119
120
def __init__(self, *args, **kwargs):
121
"""
122
Initialize PrettyPrinter with formatting options.
123
124
Parameters match those accepted by pprint() and cpprint().
125
"""
126
127
def pprint(self, object):
128
"""Pretty print object using configured settings."""
129
130
def pformat(self, object) -> str:
131
"""Format object as string using configured settings."""
132
133
def isrecursive(self, object) -> bool:
134
"""Check if object contains recursive references."""
135
136
def isreadable(self, object) -> bool:
137
"""Check if object's repr is readable."""
138
139
def format(self, object):
140
"""Format method (not implemented - raises NotImplementedError)."""
141
```
142
143
### Low-Level Functions
144
145
Core internal functions for converting Python values to documents and rendering output streams.
146
147
```python { .api }
148
def python_to_sdocs(value, indent, width, depth, ribbon_width,
149
max_seq_len, sort_dict_keys):
150
"""
151
Convert Python value to structured documents for layout processing.
152
153
This is the core function used internally by pprint, cpprint, and pformat
154
to convert Python objects into a document representation that can be
155
rendered with different output formats.
156
157
Parameters:
158
- value: Python object to convert
159
- indent: indentation level per nesting level
160
- width: target line width for layout
161
- depth: maximum depth to traverse (None for unlimited)
162
- ribbon_width: target width after indentation
163
- max_seq_len: maximum sequence length before truncation
164
- sort_dict_keys: whether to sort dictionary keys
165
166
Returns:
167
Iterator of structured documents ready for rendering
168
"""
169
170
def default_render_to_stream(stream, sdocs, newline='\n', separator=' '):
171
"""
172
Render structured documents to a text stream without syntax highlighting.
173
174
This function takes the output from python_to_sdocs and renders it as
175
plain text to a stream object.
176
177
Parameters:
178
- stream: output stream (e.g., sys.stdout, StringIO)
179
- sdocs: structured documents from python_to_sdocs
180
- newline: string to use for line endings
181
- separator: string to use between text elements
182
"""
183
```
184
185
## Usage Examples
186
187
### Basic Pretty Printing
188
189
```python
190
from prettyprinter import pprint, cpprint, pformat
191
192
# Complex nested data
193
data = {
194
'config': {
195
'database': {
196
'host': 'localhost',
197
'port': 5432,
198
'credentials': {'user': 'admin', 'pass': '***'}
199
},
200
'cache': {'redis_url': 'redis://localhost:6379', 'ttl': 3600}
201
},
202
'features': ['auth', 'logging', 'metrics'],
203
'metadata': {'version': '1.2.3', 'build': 42}
204
}
205
206
# Plain text output
207
pprint(data, width=50)
208
209
# Colored output with custom style
210
cpprint(data, width=50, style='light')
211
212
# Get as string for further processing
213
formatted_string = pformat(data, width=40, sort_dict_keys=True)
214
```
215
216
### Configuration Options
217
218
```python
219
from prettyprinter import pprint
220
221
large_list = list(range(100))
222
deep_nested = {'a': {'b': {'c': {'d': {'e': 'deep'}}}}}
223
224
# Limit sequence length
225
pprint(large_list, max_seq_len=10) # Shows first 10 items + truncation comment
226
227
# Limit nesting depth
228
pprint(deep_nested, depth=3) # Stops at depth 3 with "..."
229
230
# Custom indentation and width
231
pprint(data, indent=2, width=60, ribbon_width=50)
232
233
# Sort dictionary keys
234
pprint({'z': 1, 'a': 2, 'b': 3}, sort_dict_keys=True)
235
```
236
237
### Using PrettyPrinter Class
238
239
```python
240
from prettyprinter import PrettyPrinter
241
242
# Create configured printer
243
pp = PrettyPrinter(width=60, indent=2, sort_dict_keys=True)
244
245
# Use consistently across multiple objects
246
pp.pprint(data1)
247
pp.pprint(data2)
248
249
# Get formatted strings
250
formatted1 = pp.pformat(data1)
251
formatted2 = pp.pformat(data2)
252
```
253
254
### Custom __repr__ Integration
255
256
```python
257
from prettyprinter import pretty_repr, register_pretty
258
259
class ComplexObject:
260
def __init__(self, items):
261
self.items = items
262
self.metadata = {'created': '2024-01-01', 'count': len(items)}
263
264
# Use prettyprinter for repr
265
__repr__ = pretty_repr
266
267
# Register custom pretty printer for the class
268
@register_pretty(ComplexObject)
269
def pretty_complex_object(obj, ctx):
270
return pretty_call(ctx, ComplexObject, obj.items)
271
272
# Now instances use prettyprinter for repr
273
obj = ComplexObject([1, 2, 3, 4, 5])
274
print(obj) # Uses pretty_repr automatically
275
```