Python's missing debug print command and development tools with enhanced debugging, pretty printing, timing, and ANSI styling capabilities.
—
Cross-platform ANSI color and style formatting for terminal output with Windows console support, automatic TTY detection, and comprehensive style options. Provides both formatting functions for styled strings and direct printing with style application.
Format text with ANSI escape sequences for color and styling without printing.
def sformat(input, *styles, reset=True, apply=True) -> str:
"""
Format text with ANSI styles and return styled string.
Parameters:
- input: Text or object to style (converted to string)
- *styles: Style codes to apply (Style enum values, ints, or strings)
- reset: Append ANSI reset code at end (default: True)
- apply: Apply styling (False returns original text, default: True)
Returns:
String with ANSI escape sequences for styling
"""Usage examples:
from devtools import sformat
# Basic color formatting
red_text = sformat("Error message", sformat.red)
print(red_text) # Prints in red
# Multiple styles
bold_blue = sformat("Important", sformat.bold, sformat.blue)
print(bold_blue) # Prints in bold blue
# Background colors
highlighted = sformat("Warning", sformat.yellow, sformat.bg_red)
print(highlighted) # Yellow text on red background
# Conditional styling
def format_status(status, is_error=False):
if is_error:
return sformat(status, sformat.red, sformat.bold)
else:
return sformat(status, sformat.green)
print(format_status("Success", False)) # Green
print(format_status("Failed", True)) # Bold red
# No reset (for chaining styles)
partial = sformat("Start", sformat.bold, reset=False)
complete = partial + sformat(" End", sformat.italic)
print(complete) # "Start" in bold, " End" in bold italicPrint text with ANSI styling directly to output stream.
def sprint(input, *styles, reset=True, flush=True, file=None, **print_kwargs) -> None:
"""
Print text with ANSI styling, with automatic TTY detection.
Parameters:
- input: Text to print
- *styles: Style codes to apply
- reset: Append ANSI reset code (default: True)
- flush: Flush output buffer (default: True)
- file: Output file (default: stdout)
- **print_kwargs: Additional arguments passed to print()
"""Usage examples:
from devtools import sprint
# Basic colored printing
sprint("Success!", sprint.green)
sprint("Warning", sprint.yellow, sprint.bold)
sprint("Error occurred", sprint.red, sprint.bg_white)
# Print to file
with open('log.txt', 'w') as f:
sprint("Log entry", sprint.blue, file=f)
# Custom print arguments
sprint("Multiple", "arguments", sprint.cyan, sep=' | ', end='\n\n')
# Conditional styling based on TTY
import sys
if sys.stdout.isatty():
sprint("Terminal output", sprint.green)
else:
sprint("File output") # No styling applied to filesComprehensive enumeration of ANSI style codes with both individual values and a callable interface.
class Style(IntEnum):
"""
ANSI style codes enum with styling function capability.
"""
# Reset and text styles
reset = 0
bold = 1
not_bold = 22
dim = 2
not_dim = 22
italic = 3
not_italic = 23
underline = 4
not_underline = 24
blink = 5
not_blink = 25
reverse = 7
not_reverse = 27
strike_through = 9
not_strike_through = 29
# Foreground colors
black = 30
red = 31
green = 32
yellow = 33
blue = 34
magenta = 35
cyan = 36
white = 37
# Background colors
bg_black = 40
bg_red = 41
bg_green = 42
bg_yellow = 43
bg_blue = 44
bg_magenta = 45
bg_cyan = 46
bg_white = 47
def __call__(self, input, *styles, reset=True, apply=True) -> str:
"""
Apply ANSI styles to text (same as sformat function).
Parameters:
- input: Text to style
- *styles: Additional styles to apply
- reset: Append reset code (default: True)
- apply: Apply styling (default: True)
Returns:
Styled text string
"""
@property
def styles(self) -> dict[str, Style]:
"""
Get mapping of style names to Style enum values.
Returns:
Dictionary mapping style names to Style values
"""Usage examples:
from devtools import sformat
# Using Style enum values directly
red_bold = sformat("Alert", sformat.red, sformat.bold)
# Using string names (looked up in styles property)
yellow_text = sformat("Warning", "yellow", "underline")
# Combining foreground and background
contrast = sformat("High Contrast", sformat.white, sformat.bg_black)
# Text decorations
fancy_text = sformat("Fancy", sformat.italic, sformat.underline, sformat.cyan)
# Dim/bright variations
subtle = sformat("Subtle text", sformat.dim)
prominent = sformat("Prominent text", sformat.bold)
# Reverse video (swap foreground/background)
reversed_text = sformat("Reversed", sformat.reverse)Automatic handling of Windows console ANSI support and TTY detection.
from devtools import sformat, sprint
# Automatic Windows ANSI activation
# On Windows 10+, ANSI codes are automatically enabled
# On older Windows, gracefully falls back to plain text
# TTY detection for appropriate styling
sprint("This will be colored in terminal", sformat.green)
# When redirected to file: no ANSI codes added
# python script.py > output.txt # output.txt contains plain text
# Force styling regardless of TTY
forced_color = sformat("Always colored", sformat.blue, apply=True)
# Disable styling regardless of TTY
plain_text = sformat("Never colored", sformat.red, apply=False)Complex styling scenarios and best practices.
from devtools import sformat
# Nested styling with manual reset control
def format_log_level(level, message):
level_styles = {
'DEBUG': [sformat.dim],
'INFO': [sformat.blue],
'WARNING': [sformat.yellow, sformat.bold],
'ERROR': [sformat.red, sformat.bold],
'CRITICAL': [sformat.white, sformat.bg_red, sformat.bold]
}
if level in level_styles:
styled_level = sformat(f"[{level}]", *level_styles[level])
return f"{styled_level} {message}"
return f"[{level}] {message}"
# Progress indicators with colors
def format_progress(current, total):
percentage = (current / total) * 100
bar_length = 20
filled = int(bar_length * current / total)
bar = sformat('█' * filled, sformat.green) + \
sformat('░' * (bar_length - filled), sformat.dim)
return f"{bar} {percentage:6.1f}%"
# Status indicators
def format_status(success_count, error_count):
success = sformat(f"✓ {success_count}", sformat.green)
errors = sformat(f"✗ {error_count}", sformat.red) if error_count > 0 else ""
return f"{success} {errors}".strip()
# Table formatting with alternating row colors
def format_table_row(items, row_num):
style = sformat.dim if row_num % 2 == 0 else None
formatted_items = []
for item in items:
if style:
formatted_items.append(sformat(str(item), style))
else:
formatted_items.append(str(item))
return " | ".join(formatted_items)Integration with environment variables and terminal capabilities.
import os
from devtools import sformat
# Respect NO_COLOR environment variable
def smart_format(text, *styles):
if os.environ.get('NO_COLOR'):
return text
return sformat(text, *styles)
# Custom color schemes based on terminal
def get_theme_color(color_name):
# Adapt colors based on terminal background
dark_theme = {
'primary': sformat.cyan,
'secondary': sformat.yellow,
'success': sformat.green,
'error': sformat.red
}
return dark_theme.get(color_name, sformat.white)
# Terminal capability detection
import sys
def supports_color():
"""Check if terminal supports color output."""
return (
hasattr(sys.stdout, 'isatty') and
sys.stdout.isatty() and
os.environ.get('TERM') != 'dumb'
)# Style function instances
sformat: Style # Main formatting function (Style(-1) instance)
sprint: StylePrint # Main printing function
class StylePrint:
"""
Print function with ANSI styling support.
"""
def __call__(self, input, *styles, reset=True, flush=True, file=None, **print_kwargs) -> None: ...
def __getattr__(self, item: str) -> str: ...
def __repr__(self) -> str: ...
# Internal utility functions
def _style_as_int(v: Style | int) -> str: ...
def _as_ansi(s: str) -> str: ...Install with Tessl CLI
npx tessl i tessl/pypi-devtools