Syntax-highlighting, declarative and composable pretty printer for Python 3.5+
—
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.
Set and retrieve global default configuration values used by all pretty printing functions when explicit parameters are not provided.
def set_default_config(*, style=None, max_seq_len=None, width=None,
ribbon_width=None, depth=None, sort_dict_keys=None):
"""
Set default configuration values for pretty printing functions.
Parameters:
- style: Default color style for cpprint ('light', 'dark', or Style subclass)
- max_seq_len (int): Default maximum sequence length before truncation
- width (int): Default soft maximum columns in output
- ribbon_width (int): Default soft maximum columns after indenting
- depth (int): Default maximum depth for nested structures
- sort_dict_keys (bool): Default whether to sort dictionary keys
Returns:
- dict: Updated configuration dictionary
Notes:
- Only provided parameters are updated; others retain current values
- Changes affect all subsequent pretty printing operations
- Style parameter also calls set_default_style()
"""
def get_default_config():
"""
Get read-only view of current default configuration.
Returns:
- MappingProxyType: Read-only mapping of current configuration values
Configuration keys:
- 'indent': Number of spaces per nesting level (default: 4)
- 'width': Soft maximum columns in output (default: 79)
- 'ribbon_width': Soft maximum columns after indenting (default: 71)
- 'depth': Maximum depth for nested structures (default: None)
- 'max_seq_len': Maximum sequence length before truncation (default: 1000)
- 'sort_dict_keys': Whether to sort dictionary keys (default: False)
"""Configure default color schemes and syntax highlighting options for colored pretty printing output.
def set_default_style(style):
"""
Set default global style for colored pretty printing with cpprint.
Parameters:
- style: Style specification
- 'dark': Use dark theme (monokai)
- 'light': Use light theme (GitHub light)
- Style subclass: Custom Pygments Style class
Raises:
- TypeError: If style is not a Style subclass or valid string
Notes:
- Affects all subsequent cpprint() calls when style parameter is not specified
- Environment variables COLORFGBG and PYPRETTYPRINTER_LIGHT_BACKGROUND affect auto-detection
"""from prettyprinter import set_default_config, get_default_config, pprint
# View current configuration
current_config = get_default_config()
print(current_config)
# {'indent': 4, 'width': 79, 'ribbon_width': 71, 'depth': None,
# 'max_seq_len': 1000, 'sort_dict_keys': False}
# Set new defaults for all operations
set_default_config(
width=60,
indent=2,
max_seq_len=50,
sort_dict_keys=True
)
# Now all pprint calls use these defaults
data = {'zebra': 1, 'alpha': 2, 'beta': 3}
pprint(data) # Uses width=60, indent=2, sort_dict_keys=True
# Long sequences are truncated at 50 items
long_list = list(range(100))
pprint(long_list) # Shows first 50 items + "...and 50 more elements"from prettyprinter import set_default_style, cpprint
# Set light theme as default
set_default_style('light')
# All cpprint calls now use light theme by default
data = {'numbers': [1, 2, 3], 'text': 'hello world'}
cpprint(data) # Uses light theme
# Set dark theme
set_default_style('dark')
cpprint(data) # Uses dark theme
# Custom style using Pygments
from pygments.style import Style
from pygments.token import *
class CustomStyle(Style):
styles = {
Number: '#00ff00 bold',
String: '#ff0000',
Name: '#0000ff',
}
set_default_style(CustomStyle)
cpprint(data) # Uses custom colorsfrom prettyprinter import set_default_config, get_default_config, pprint
# Save current configuration
original_config = dict(get_default_config())
# Set temporary configuration
set_default_config(width=40, indent=8)
# Use temporary settings
pprint(complex_data)
# Restore original configuration
set_default_config(**original_config)import os
from prettyprinter import set_default_config, set_default_style
# Configure based on environment
if os.getenv('DEBUG'):
set_default_config(
width=120,
depth=10,
sort_dict_keys=True # Consistent output for debugging
)
else:
set_default_config(
width=80,
depth=3,
max_seq_len=20 # Abbreviated output for production
)
# Set style based on terminal background
if os.getenv('TERM_BACKGROUND') == 'light':
set_default_style('light')
else:
set_default_style('dark')from prettyprinter import set_default_config, get_default_config
from contextlib import contextmanager
@contextmanager
def temp_config(**kwargs):
"""Context manager for temporary configuration changes."""
original = dict(get_default_config())
set_default_config(**kwargs)
try:
yield
finally:
set_default_config(**original)
# Usage
with temp_config(width=40, sort_dict_keys=True):
pprint(data1) # Uses temporary settings
pprint(data2) # Uses temporary settings
pprint(data3) # Back to original settingsfrom prettyprinter import set_default_config, set_default_style
def configure_prettyprinter(*,
debug_mode=False,
terminal_width=None,
color_scheme='auto'):
"""Configure prettyprinter for application use."""
# Base configuration
config = {
'sort_dict_keys': True, # Consistent output
'max_seq_len': 100 if debug_mode else 20,
'depth': None if debug_mode else 5
}
# Terminal width detection
if terminal_width:
config['width'] = terminal_width
config['ribbon_width'] = max(terminal_width - 8, 40)
else:
try:
import shutil
width = shutil.get_terminal_size().columns
config['width'] = min(width, 120)
config['ribbon_width'] = config['width'] - 8
except:
pass # Use defaults
set_default_config(**config)
# Color scheme
if color_scheme == 'auto':
# Let prettyprinter auto-detect
pass
elif color_scheme in ('light', 'dark'):
set_default_style(color_scheme)
# Initialize for application
configure_prettyprinter(debug_mode=True, color_scheme='dark')from prettyprinter import get_default_config
def print_config_summary():
"""Display current prettyprinter configuration."""
config = get_default_config()
print("PrettyPrinter Configuration:")
print(f" Width: {config['width']} columns")
print(f" Ribbon Width: {config['ribbon_width']} columns")
print(f" Indentation: {config['indent']} spaces per level")
print(f" Max Depth: {config['depth'] or 'unlimited'}")
print(f" Max Sequence Length: {config['max_seq_len']}")
print(f" Sort Dict Keys: {config['sort_dict_keys']}")
print_config_summary()Install with Tessl CLI
npx tessl i tessl/pypi-prettyprinter