CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-boltons

When they're not builtins, they're boltons.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

development-debugging-tools.mddocs/

Development & Debugging Tools

Debugging utilities, function introspection, traceback enhancement, garbage collection tools, and development aids. Includes pdb integration, enhanced exception handling, function manipulation utilities, and comprehensive development tooling.

Capabilities

Debugging Integration

Integration with Python's pdb debugger for enhanced debugging workflows.

def pdb_on_signal(signalnum=None):
    """
    Install signal handler to launch pdb breakpoint.
    
    Parameters:
    - signalnum (int, optional): Signal number (default: SIGUSR1)
    
    Returns:
    None
    """

def pdb_on_exception(limit=100):
    """
    Install handler for post-mortem pdb on unhandled exceptions.
    
    Parameters:
    - limit (int): Traceback limit
    
    Returns:
    None
    """

def wrap_trace(obj, hook=trace_print_hook, **kwargs):
    """
    Monitor object interactions with custom tracing.
    
    Parameters:
    - obj: Object to trace
    - hook (callable): Trace event handler
    
    Returns:
    Wrapped object with tracing
    """

def trace_print_hook(event, label, obj, attr_name, **kwargs):
    """
    Default hook for printing trace events.
    
    Parameters:
    - event (str): Event type ('get', 'set', 'call', etc.)
    - label (str): Trace label
    - obj: Target object
    - attr_name (str): Attribute name
    
    Returns:
    None
    """

Enhanced Traceback Handling

Comprehensive traceback inspection and formatting utilities.

class Callpoint:
    """Represents a single point in a call stack."""
    def __init__(self, tb_frame, lineno): ...
    @property
    def filename(self): ...
    @property
    def lineno(self): ...
    @property
    def func_name(self): ...
    @property
    def module_name(self): ...
    def __repr__(self): ...

class TracebackInfo:
    """Enhanced traceback information with additional context."""
    def __init__(self, tb): ...
    @property
    def callpoints(self): ...
    def format(self): ...
    def to_dict(self): ...

class ExceptionInfo:
    """Enhanced exception information with formatting."""
    def __init__(self, exc_type, exc_value, exc_tb): ...
    @property
    def exc_type(self): ...
    @property
    def exc_msg(self): ...
    @property
    def tb_info(self): ...
    def format(self): ...

class ContextualCallpoint(Callpoint):
    """Callpoint with source code context."""
    @property
    def source_lines(self): ...
    @property
    def source_context(self): ...

class ContextualTracebackInfo(TracebackInfo):
    """TracebackInfo with source context."""
    pass

class ContextualExceptionInfo(ExceptionInfo):
    """ExceptionInfo with source context."""
    pass

class ParsedException:
    """Parsed exception from string representation."""
    def __init__(self, exc_str): ...
    @property
    def exc_type_name(self): ...
    @property
    def exc_msg(self): ...

def format_exception_only(etype, value):
    """
    Format exception without traceback.
    
    Parameters:
    - etype (type): Exception type
    - value (Exception): Exception instance
    
    Returns:
    str: Formatted exception string
    """

def print_exception(etype, value, tb, **kwargs):
    """
    Enhanced exception printing.
    
    Parameters:
    - etype (type): Exception type
    - value (Exception): Exception instance
    - tb: Traceback object
    
    Returns:
    None
    """

def fix_print_exception():
    """
    Monkey-patch sys.excepthook with enhanced version.
    
    Returns:
    None
    """

Function Introspection and Manipulation

Comprehensive function analysis and manipulation utilities.

def get_module_callables(mod, ignore=None):
    """
    Get all callable objects from a module.
    
    Parameters:
    - mod: Module to inspect
    - ignore (set, optional): Names to ignore
    
    Returns:
    dict: Mapping of names to callable objects
    """

def mro_items(type_obj):
    """
    Get method resolution order as (name, class) pairs.
    
    Parameters:
    - type_obj (type): Type to analyze
    
    Returns:
    list: List of (method_name, defining_class) tuples
    """

def dir_dict(obj, raise_exc=False):
    """
    Get object's __dict__ with error handling.
    
    Parameters:
    - obj: Object to inspect
    - raise_exc (bool): Raise exceptions on access errors
    
    Returns:
    dict: Object's attributes dictionary
    """

def copy_function(orig, copy_dict=True):
    """
    Create copy of function object.
    
    Parameters:
    - orig (function): Original function
    - copy_dict (bool): Copy function's __dict__
    
    Returns:
    function: Copied function
    """

def partial_ordering(cls):
    """
    Class decorator to add comparison methods from __lt__.
    
    Parameters:
    - cls (type): Class to enhance
    
    Returns:
    type: Enhanced class with comparison methods
    """

class FunctionBuilder:
    """Programmatically build function signatures and implementations."""
    def __init__(self, name, doc=None, defaults=None, **kwargs): ...
    def add_arg(self, name, default=NO_DEFAULT): ...
    def add_kwarg(self, name, default): ...
    def compile(self, execdict=None): ...

def format_invocation(name='', args=(), kwargs=None, **kw):
    """
    Format function call as string.
    
    Parameters:
    - name (str): Function name
    - args (tuple): Positional arguments
    - kwargs (dict): Keyword arguments
    
    Returns:
    str: Formatted function call
    """

def wraps(func, injected=None, expected=None, **kw):
    """
    Enhanced functools.wraps.
    
    Parameters:
    - func (callable): Function to wrap
    - injected (list): Injected argument names
    - expected (list): Expected argument names
    
    Returns:
    callable: Decorator function
    """

def noop(*args, **kwargs):
    """
    No-operation function.
    
    Parameters:
    - *args: Any positional arguments (ignored)
    - **kwargs: Any keyword arguments (ignored)
    
    Returns:
    None
    """

Garbage Collection Utilities

Tools for analyzing and controlling garbage collection.

class GCToggler:
    """Context manager to temporarily disable/enable garbage collection."""
    def __init__(self, enabled=False): ...
    def __enter__(self): ...
    def __exit__(self, exc_type, exc_val, exc_tb): ...

def get_all(type_obj, include_subtypes=True):
    """
    Get all instances of a type from GC.
    
    Parameters:
    - type_obj (type): Type to search for
    - include_subtypes (bool): Include subtype instances
    
    Returns:
    list: List of instances found in GC
    """

Usage Examples

from boltons.debugutils import pdb_on_signal, pdb_on_exception, wrap_trace
from boltons.tbutils import TracebackInfo, ExceptionInfo
from boltons.funcutils import FunctionBuilder, get_module_callables
from boltons.gcutils import GCToggler, get_all
import signal

# Enhanced debugging setup
pdb_on_signal(signal.SIGUSR1)  # Send SIGUSR1 to drop into debugger
pdb_on_exception()             # Auto-debug on unhandled exceptions

# Trace object interactions
class TracedClass:
    def method(self):
        return "traced"

traced_obj = wrap_trace(TracedClass())
traced_obj.method()  # Prints trace information

# Enhanced exception handling
try:
    raise ValueError("Something went wrong")
except:
    import sys
    exc_info = ExceptionInfo(*sys.exc_info())
    print(exc_info.format())  # Enhanced exception formatting

# Function analysis
import math
callables = get_module_callables(math)
print(f"Math module has {len(callables)} callable functions")

# Dynamic function building
builder = FunctionBuilder('dynamic_func', doc='Dynamically created function')
builder.add_arg('x')
builder.add_arg('y', default=10)
builder.add_kwarg('multiply', default=True)

func_code = '''
if multiply:
    return x * y
else:
    return x + y
'''

dynamic_func = builder.compile({'multiply': True})
# Now dynamic_func(5, y=3, multiply=False) works

# Garbage collection analysis
class TestClass:
    pass

instances = [TestClass() for _ in range(10)]
found_instances = get_all(TestClass)
print(f"Found {len(found_instances)} TestClass instances in GC")

# Temporarily disable GC for performance-critical section
with GCToggler(enabled=False):
    # Perform operations without GC interruption
    heavy_computation()

Advanced Development Tools

from boltons.funcutils import copy_function, format_invocation, wraps
from boltons.tbutils import ContextualExceptionInfo

# Function copying and modification
def original_func(x, y=5):
    \"\"\"Original function docstring.\"\"\"
    return x + y

copied_func = copy_function(original_func)
copied_func.__name__ = 'modified_func'
copied_func.__doc__ = 'Modified function docstring.'

# Enhanced wrapper with injection
@wraps(original_func, injected=['logger'])
def logged_wrapper(logger, *args, **kwargs):
    call_str = format_invocation('original_func', args, kwargs)
    logger.info(f"Calling: {call_str}")
    return original_func(*args, **kwargs)

# Contextual exception analysis
try:
    def problematic_function():
        x = 1 / 0  # Division by zero
        return x
    
    problematic_function()
except:
    import sys
    ctx_exc_info = ContextualExceptionInfo(*sys.exc_info())
    
    # Get detailed context with source code
    formatted = ctx_exc_info.format()
    print("Detailed exception with source context:")
    print(formatted)
    
    # Access individual callpoints with context
    for callpoint in ctx_exc_info.tb_info.callpoints:
        if hasattr(callpoint, 'source_context'):
            print(f"Function: {callpoint.func_name}")
            print(f"Source context around line {callpoint.lineno}:")
            for line_no, line in callpoint.source_context:
                marker = ">>>" if line_no == callpoint.lineno else "   "
                print(f"{marker} {line_no}: {line}")

Types

# Exception classes
class MissingArgument(ValueError):
    \"\"\"Exception for missing function arguments.\"\"\"
    pass

class ExistingArgument(ValueError):
    \"\"\"Exception for conflicting function arguments.\"\"\"
    pass

# Sentinel values
NO_DEFAULT = object()  # Sentinel for arguments with no default value

# Trace event types
TRACE_EVENTS = {'get', 'set', 'call', 'return', 'exception'}

Install with Tessl CLI

npx tessl i tessl/pypi-boltons

docs

additional-utilities.md

caching.md

data-structures.md

development-debugging-tools.md

file-io-operations.md

format-table-utilities.md

index.md

iteration-processing.md

math-stats-operations.md

network-url-handling.md

string-text-processing.md

time-date-utilities.md

tile.json