0
# Configuration Management
1
2
Functions for managing global configuration settings and styling options that affect all pretty printing operations. This system allows setting default values that persist across multiple print operations.
3
4
## Capabilities
5
6
### Global Configuration
7
8
Set and retrieve global default configuration values used by all pretty printing functions when explicit parameters are not provided.
9
10
```python { .api }
11
def set_default_config(*, style=None, max_seq_len=None, width=None,
12
ribbon_width=None, depth=None, sort_dict_keys=None):
13
"""
14
Set default configuration values for pretty printing functions.
15
16
Parameters:
17
- style: Default color style for cpprint ('light', 'dark', or Style subclass)
18
- max_seq_len (int): Default maximum sequence length before truncation
19
- width (int): Default soft maximum columns in output
20
- ribbon_width (int): Default soft maximum columns after indenting
21
- depth (int): Default maximum depth for nested structures
22
- sort_dict_keys (bool): Default whether to sort dictionary keys
23
24
Returns:
25
- dict: Updated configuration dictionary
26
27
Notes:
28
- Only provided parameters are updated; others retain current values
29
- Changes affect all subsequent pretty printing operations
30
- Style parameter also calls set_default_style()
31
"""
32
33
def get_default_config():
34
"""
35
Get read-only view of current default configuration.
36
37
Returns:
38
- MappingProxyType: Read-only mapping of current configuration values
39
40
Configuration keys:
41
- 'indent': Number of spaces per nesting level (default: 4)
42
- 'width': Soft maximum columns in output (default: 79)
43
- 'ribbon_width': Soft maximum columns after indenting (default: 71)
44
- 'depth': Maximum depth for nested structures (default: None)
45
- 'max_seq_len': Maximum sequence length before truncation (default: 1000)
46
- 'sort_dict_keys': Whether to sort dictionary keys (default: False)
47
"""
48
```
49
50
### Style Configuration
51
52
Configure default color schemes and syntax highlighting options for colored pretty printing output.
53
54
```python { .api }
55
def set_default_style(style):
56
"""
57
Set default global style for colored pretty printing with cpprint.
58
59
Parameters:
60
- style: Style specification
61
- 'dark': Use dark theme (monokai)
62
- 'light': Use light theme (GitHub light)
63
- Style subclass: Custom Pygments Style class
64
65
Raises:
66
- TypeError: If style is not a Style subclass or valid string
67
68
Notes:
69
- Affects all subsequent cpprint() calls when style parameter is not specified
70
- Environment variables COLORFGBG and PYPRETTYPRINTER_LIGHT_BACKGROUND affect auto-detection
71
"""
72
```
73
74
## Usage Examples
75
76
### Setting Global Defaults
77
78
```python
79
from prettyprinter import set_default_config, get_default_config, pprint
80
81
# View current configuration
82
current_config = get_default_config()
83
print(current_config)
84
# {'indent': 4, 'width': 79, 'ribbon_width': 71, 'depth': None,
85
# 'max_seq_len': 1000, 'sort_dict_keys': False}
86
87
# Set new defaults for all operations
88
set_default_config(
89
width=60,
90
indent=2,
91
max_seq_len=50,
92
sort_dict_keys=True
93
)
94
95
# Now all pprint calls use these defaults
96
data = {'zebra': 1, 'alpha': 2, 'beta': 3}
97
pprint(data) # Uses width=60, indent=2, sort_dict_keys=True
98
99
# Long sequences are truncated at 50 items
100
long_list = list(range(100))
101
pprint(long_list) # Shows first 50 items + "...and 50 more elements"
102
```
103
104
### Style Configuration
105
106
```python
107
from prettyprinter import set_default_style, cpprint
108
109
# Set light theme as default
110
set_default_style('light')
111
112
# All cpprint calls now use light theme by default
113
data = {'numbers': [1, 2, 3], 'text': 'hello world'}
114
cpprint(data) # Uses light theme
115
116
# Set dark theme
117
set_default_style('dark')
118
cpprint(data) # Uses dark theme
119
120
# Custom style using Pygments
121
from pygments.style import Style
122
from pygments.token import *
123
124
class CustomStyle(Style):
125
styles = {
126
Number: '#00ff00 bold',
127
String: '#ff0000',
128
Name: '#0000ff',
129
}
130
131
set_default_style(CustomStyle)
132
cpprint(data) # Uses custom colors
133
```
134
135
### Temporary Configuration Changes
136
137
```python
138
from prettyprinter import set_default_config, get_default_config, pprint
139
140
# Save current configuration
141
original_config = dict(get_default_config())
142
143
# Set temporary configuration
144
set_default_config(width=40, indent=8)
145
146
# Use temporary settings
147
pprint(complex_data)
148
149
# Restore original configuration
150
set_default_config(**original_config)
151
```
152
153
### Environment-Based Configuration
154
155
```python
156
import os
157
from prettyprinter import set_default_config, set_default_style
158
159
# Configure based on environment
160
if os.getenv('DEBUG'):
161
set_default_config(
162
width=120,
163
depth=10,
164
sort_dict_keys=True # Consistent output for debugging
165
)
166
else:
167
set_default_config(
168
width=80,
169
depth=3,
170
max_seq_len=20 # Abbreviated output for production
171
)
172
173
# Set style based on terminal background
174
if os.getenv('TERM_BACKGROUND') == 'light':
175
set_default_style('light')
176
else:
177
set_default_style('dark')
178
```
179
180
### Configuration Context Manager
181
182
```python
183
from prettyprinter import set_default_config, get_default_config
184
from contextlib import contextmanager
185
186
@contextmanager
187
def temp_config(**kwargs):
188
"""Context manager for temporary configuration changes."""
189
original = dict(get_default_config())
190
set_default_config(**kwargs)
191
try:
192
yield
193
finally:
194
set_default_config(**original)
195
196
# Usage
197
with temp_config(width=40, sort_dict_keys=True):
198
pprint(data1) # Uses temporary settings
199
pprint(data2) # Uses temporary settings
200
201
pprint(data3) # Back to original settings
202
```
203
204
### Application-Wide Configuration
205
206
```python
207
from prettyprinter import set_default_config, set_default_style
208
209
def configure_prettyprinter(*,
210
debug_mode=False,
211
terminal_width=None,
212
color_scheme='auto'):
213
"""Configure prettyprinter for application use."""
214
215
# Base configuration
216
config = {
217
'sort_dict_keys': True, # Consistent output
218
'max_seq_len': 100 if debug_mode else 20,
219
'depth': None if debug_mode else 5
220
}
221
222
# Terminal width detection
223
if terminal_width:
224
config['width'] = terminal_width
225
config['ribbon_width'] = max(terminal_width - 8, 40)
226
else:
227
try:
228
import shutil
229
width = shutil.get_terminal_size().columns
230
config['width'] = min(width, 120)
231
config['ribbon_width'] = config['width'] - 8
232
except:
233
pass # Use defaults
234
235
set_default_config(**config)
236
237
# Color scheme
238
if color_scheme == 'auto':
239
# Let prettyprinter auto-detect
240
pass
241
elif color_scheme in ('light', 'dark'):
242
set_default_style(color_scheme)
243
244
# Initialize for application
245
configure_prettyprinter(debug_mode=True, color_scheme='dark')
246
```
247
248
### Configuration Inspection
249
250
```python
251
from prettyprinter import get_default_config
252
253
def print_config_summary():
254
"""Display current prettyprinter configuration."""
255
config = get_default_config()
256
257
print("PrettyPrinter Configuration:")
258
print(f" Width: {config['width']} columns")
259
print(f" Ribbon Width: {config['ribbon_width']} columns")
260
print(f" Indentation: {config['indent']} spaces per level")
261
print(f" Max Depth: {config['depth'] or 'unlimited'}")
262
print(f" Max Sequence Length: {config['max_seq_len']}")
263
print(f" Sort Dict Keys: {config['sort_dict_keys']}")
264
265
print_config_summary()
266
```