Toolkits Module
The toolkits module provides a comprehensive collection of utility functions, decorators, and context managers designed to enhance Python applications with robust functionality for debugging, profiling, caching, logging, multithreading, and more.
Key Features
Console Output Control
Type Checking Utilities
Decorators for Various Purposes
Context Managers
Multithreading Utilities
Network Connectivity Tools
Singleton Pattern Implementation
Pointer and Memory Management
Constants Management
Deferred Value Processing
Console Output Control
- stop_console_printing(include_stderr: bool = False) None
Redirects standard output (and optionally standard error) to null device.
- Parameters:
include_stderr (bool) – If True, also redirects stderr to null device
- Raises:
UserWarning – If include_stderr is True
Type Checking Utilities
Decorators
- trace(func: Callable[..., T]) Callable[..., T]
A decorator that traces function calls and their results.
- profile(func: Callable) Callable
Simple profiling wrapper using ‘cProfile’.
- simple_debugger(func: Callable) Callable
A decorator that provides simple debugging capabilities.
- retry(exception: Type[Exception] = Exception, max_attempts: int = 5, delay: float = 1.0) Callable
A decorator that retries a function execution upon specified exception.
- param exception:
The exception type to catch and retry on
- param max_attempts:
Maximum number of retry attempts
- param delay:
Delay in seconds between retries
- simple_exception(func: Callable) Callable
A decorator that provides simple exception handling and logging.
- memoize(func: Callable[P, T]) Callable[P, T]
Caches the results of function calls based on input arguments.
- run_once(func: Callable) Callable
Ensures a function is executed only once.
- monitor(func: Callable) Callable
Monitors and logs function execution time and status.
- multithreaded(max_workers: int = 5) Callable
Executes a function in multiple threads.
- Parameters:
max_workers – Maximum number of worker threads
- singleton(cls: Type[T]) Type[T]
Decorator that implements the singleton pattern.
Context Managers
- log_level(level: int, name: str) ContextManager[logging.Logger]
Temporarily changes the logging level of a logger within a context.
- Parameters:
level – The logging level to set
name – The name of the logger
- Yields:
The logger with the temporarily changed level
Utility Functions
Classes
Constants
- class Constants
A class for creating immutable constant objects.
Pointer
DeferredValue
UnifiedOperation
- class UnifiedOperation
A descriptor that handles both sync and async operations transparently. The actual implementation is chosen based on the caller’s context.
- static create_unified_operation(sync_fn: Callable[P, R], async_fn: Callable[P, Awaitable[R]]) UnifiedOperation
Helper method to create unified operations with proper type hints.
Examples
Console Output Control:
# Suppress all console output
stop_console_printing()
print("This won't be displayed")
start_console_printing()
print("This will be displayed")
Type Checking:
assert is_iterable([1, 2, 3]) == True
assert is_iterator(iter([1, 2, 3])) == True
assert is_generator((x for x in range(3))) == True
Decorators:
@retry(exception=ValueError, max_attempts=3)
def may_fail():
# Function that might raise ValueError
@memoize
def expensive_computation(x):
# Results will be cached based on input x
@singleton
class DatabaseConnection:
# Only one instance will ever be created
Context Managers:
with log_level(logging.DEBUG, "my_logger"):
# Temporarily increase logging detail
logger.debug("Detailed information")
with ignore_warnings():
# Warnings will be suppressed in this block
warnings.warn("This warning is suppressed")
Constants and Pointers:
# Create immutable constants
config = Constants.from_dict(
HOST="localhost",
PORT=8080,
DEBUG=True
)
# Use pointer-like behavior
ptr1 = Pointer(42)
ptr2 = Pointer(None)
ptr2.point_to(ptr1)
assert ptr2.get() == 42
Deferred Values:
# Create a deferred value that updates based on CPU frequency
dv = DeferredValue(initial_value=100)
dv.set(200) # Update will be deferred
current_value = dv.get() # Get the current value
Notes
All decorators can be used with or without arguments thanks to the
make_decorator()utility.The module is designed with type safety in mind and includes comprehensive type hints.
Memory management utilities like
PointerandDeferredValueprovide fine-grained control when needed.Thread safety is ensured in relevant components through proper locking mechanisms.