When they're not builtins, they're boltons.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Specialized utilities for JSON processing, mailbox handling, named tuples/lists, type checking, environment profiling, exception handling, and deprecation management. These utilities provide essential functionality for specific use cases and system integration.
JSON Lines format processing and utilities.
class JSONLIterator:
"""Iterator for reading JSON Lines format files."""
def __init__(self, file_obj): ...
def __iter__(self): ...
def __next__(self): ...
def reverse_iter_lines(file_obj, blocksize=DEFAULT_BLOCKSIZE, **kwargs):
"""
Iterate file lines in reverse order.
Parameters:
- file_obj: File object to read
- blocksize (int): Block size for reading
Yields:
str: Each line in reverse order
"""Enhanced namedtuple and mutable namedlist implementations.
def namedtuple(typename, field_names, verbose=False, rename=False):
"""
Enhanced namedtuple factory.
Parameters:
- typename (str): Name of the new tuple subclass
- field_names (str or list): Field names for the tuple
- verbose (bool): Print class definition if True
- rename (bool): Replace invalid field names with valid ones
Returns:
type: New namedtuple class
"""
def namedlist(typename, field_names, verbose=False, rename=False):
"""
Mutable namedtuple equivalent.
Parameters:
- typename (str): Name of the new list subclass
- field_names (str or list): Field names for the list
- verbose (bool): Print class definition if True
- rename (bool): Replace invalid field names with valid ones
Returns:
type: New namedlist class with mutable fields
"""Enhanced type checking and sentinel object creation.
def make_sentinel(name='_MISSING', var_name=None):
"""
Create unique sentinel objects.
Parameters:
- name (str): Name for the sentinel
- var_name (str, optional): Variable name for representation
Returns:
Sentinel: Unique sentinel object
"""
def issubclass(subclass, baseclass):
"""
Enhanced issubclass with better error handling.
Parameters:
- subclass: Potential subclass to check
- baseclass: Base class or tuple of base classes
Returns:
bool: True if subclass is a subclass of baseclass
"""
def get_all_subclasses(cls):
"""
Get all subclasses recursively.
Parameters:
- cls (type): Base class
Returns:
set: Set of all subclasses
"""
class Sentinel:
"""Unique sentinel object for special values."""
def __init__(self, name, var_name=None): ...
def __repr__(self): ...
def __bool__(self): ...
__nonzero__ = __bool__ # Python 2 compatibility
class classproperty:
"""Property descriptor for class-level properties."""
def __init__(self, func): ...
def __get__(self, obj, objtype=None): ...System environment analysis and profiling utilities.
def get_profile(**kwargs):
"""
Main entrypoint returning JSON-serializable system info dict.
Parameters:
- **kwargs: Additional profile options
Returns:
dict: Comprehensive system profile information
"""
def get_python_info():
"""
Collect Python interpreter information.
Returns:
dict: Python interpreter details
"""
def get_profile_json(indent=False):
"""
Get profile as JSON string.
Parameters:
- indent (bool): Pretty-print JSON with indentation
Returns:
str: JSON-formatted profile data
"""
def dumps(val, indent):
"""
JSON serialization with optional indentation.
Parameters:
- val: Value to serialize
- indent (bool or int): Indentation for pretty-printing
Returns:
str: JSON-serialized string
"""Utilities for working with mbox mailbox files.
class mbox_readonlydir:
"""Read-only directory-like access to mbox files."""
def __init__(self, path, maxmem=DEFAULT_MAXMEM): ...
def __getitem__(self, key): ...
def __iter__(self): ...
def keys(self): ...
def values(self): ...
def items(self): ...
def get(self, key, default=None): ...Tools for managing deprecated module members and functionality.
class DeprecatableModule(ModuleType):
"""Module wrapper that warns on deprecated member access."""
def __init__(self, name, deprecated_members=None): ...
def __getattr__(self, name): ...
def deprecate_module_member(mod_name, name, message):
"""
Mark a module member as deprecated.
Parameters:
- mod_name (str): Module name
- name (str): Member name to deprecate
- message (str): Deprecation warning message
Returns:
None
"""Example exception handling utilities.
class ExceptionCauseMixin(Exception):
"""Mixin for exceptions that can have causes."""
def __init__(self, *args, **kwargs): ...
@property
def cause(self): ...
class MathError(ExceptionCauseMixin, ValueError):
"""Example math-related exception."""
pass
def whoops_math():
"""Example function demonstrating exception handling."""
try:
return math_lol()
except Exception as e:
raise MathError("Math operation failed") from e
def math_lol(n=0):
"""Example recursive math function."""
if n > 10:
raise ValueError("Number too large")
return n * math_lol(n + 1) if n < 5 else 1Novelty functions and easter eggs.
def gobs_program():
"""
Pure-Python implementation of Gob's Algorithm.
Returns:
str: Result of Gob's Algorithm (novelty function)
"""from boltons.jsonutils import JSONLIterator
from boltons.namedutils import namedtuple, namedlist
from boltons.typeutils import make_sentinel, issubclass
from boltons.ecoutils import get_profile
# JSON Lines processing
with open('data.jsonl', 'r') as f:
jsonl_iter = JSONLIterator(f)
for record in jsonl_iter:
print(f"Processing: {record}")
# Enhanced namedtuple
Person = namedtuple('Person', 'name age city', verbose=True)
alice = Person('Alice', 30, 'New York')
print(f"Name: {alice.name}, Age: {alice.age}")
# Mutable namedlist
MutablePerson = namedlist('MutablePerson', 'name age city')
bob = MutablePerson('Bob', 25, 'Los Angeles')
bob.age = 26 # Can modify fields
print(f"Updated age: {bob.age}")
# Sentinel objects for special values
MISSING = make_sentinel('MISSING')
DEFAULT = make_sentinel('DEFAULT', 'DEFAULT_VALUE')
def process_data(data, strategy=MISSING):
if strategy is MISSING:
print("No strategy specified")
elif strategy is DEFAULT:
print("Using default strategy")
else:
print(f"Using strategy: {strategy}")
process_data([1, 2, 3]) # No strategy specified
process_data([1, 2, 3], DEFAULT) # Using default strategy
# Enhanced type checking
class Animal: pass
class Dog(Animal): pass
class Puppy(Dog): pass
print(issubclass(Dog, Animal)) # True
print(issubclass("not a class", Animal)) # False (no TypeError)
from boltons.typeutils import get_all_subclasses
all_subs = get_all_subclasses(Animal)
print(f"Animal subclasses: {all_subs}") # {Dog, Puppy}
# System profiling
profile = get_profile()
print(f"Python version: {profile['python']['version']}")
print(f"Platform: {profile['system']['platform']}")
print(f"Architecture: {profile['system']['architecture']}")from boltons.ecoutils import get_python_info, get_profile_json
from boltons.deprutils import DeprecatableModule, deprecate_module_member
from boltons.mboxutils import mbox_readonlydir
import tempfile
import warnings
# Detailed Python environment analysis
python_info = get_python_info()
print("Python Environment Details:")
for key, value in python_info.items():
print(f" {key}: {value}")
# Export environment profile as JSON
profile_json = get_profile_json(indent=True)
with open('system_profile.json', 'w') as f:
f.write(profile_json)
# Deprecation management
# Create a module with deprecated members
class MyModule(DeprecatableModule):
def __init__(self):
super().__init__('mymodule')
self.new_function = lambda: "This is the new function"
self._deprecated_members = {
'old_function': 'old_function is deprecated, use new_function instead'
}
my_module = MyModule()
# Access deprecated member (will issue warning)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
try:
result = my_module.old_function # Triggers deprecation warning
except AttributeError:
print("Deprecated member access blocked")
if w:
print(f"Warning: {w[0].message}")
# Mailbox processing (if mbox file exists)
# mbox_dir = mbox_readonlydir('/path/to/mailbox.mbox')
# for message_id in mbox_dir.keys():
# message = mbox_dir[message_id]
# print(f"Message {message_id}: {message['Subject']}")
# Class-level properties
class ConfigManager:
_instance = None
_config = {'debug': False, 'version': '1.0'}
@classproperty
def config(cls):
return cls._config
@classproperty
def debug_mode(cls):
return cls._config.get('debug', False)
print(f"Debug mode: {ConfigManager.debug_mode}")
print(f"Config: {ConfigManager.config}")
# Exception handling with causes
from boltons.excutils import ExceptionCauseMixin
class DataProcessingError(ExceptionCauseMixin):
pass
def process_file(filename):
try:
with open(filename, 'r') as f:
data = f.read()
return json.loads(data) # Might raise JSONDecodeError
except FileNotFoundError as e:
raise DataProcessingError(f"Could not find file: {filename}") from e
except json.JSONDecodeError as e:
raise DataProcessingError(f"Invalid JSON in file: {filename}") from e
# The resulting exception will have both the original cause and new context# Constants
ECO_VERSION = '1.1.0' # Protocol version for environment profiles
DEFAULT_BLOCKSIZE = 4096 # Default block size for file operations
DEFAULT_MAXMEM = 4 * 1024 * 1024 # Default memory limit (4MB)
# Environment profile components
INSTANCE_ID: str # Unique 128-bit identifier for current process
START_TIME_INFO: dict # Dictionary with startup time information
# Sentinel type
SentinelType = type(make_sentinel()) # Type of sentinel objectsInstall with Tessl CLI
npx tessl i tessl/pypi-boltons