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

start_console_printing() None

Restores standard output and standard error to their original values.

stop_print() None

Replaces the built-in print function with an empty function.

start_print() None

Restores the built-in print function to its original state.

Type Checking Utilities

is_iterable(x: Any) bool

Checks if an object is iterable.

is_iterator(x: Any) bool

Checks if an object is an iterator.

is_generator(x: Any) bool

Checks if an object is a generator.

is_hashable(value: T) bool

Checks if a value is hashable.

is_mutable(value: T) bool

Checks if a value is mutable.

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

ignore_warnings() ContextManager[None]

Context manager to temporarily suppress all warnings.

Utility Functions

get_module_size(module: Any) int

Calculates the approximate memory size of a module.

find_path(node: str, cwd: str = '.') str | None

Search for a file ‘node’ starting from the directory ‘cwd’.

check_internet_connectivity(url: str) None

Checks if there is an active internet connection to the specified URL.

Parameters:

url – The URL to check connectivity against

Raises:

URLError – If connection cannot be established

Classes

Constants

class Constants

A class for creating immutable constant objects.

classmethod from_dict(**kwargs) Constants

Create a Constants instance from a dictionary.

classmethod from_nonmapping_iterable(iterable: Iterable[Tuple[str, Any]]) Constants

Create a Constants instance from an iterable of key-value pairs.

Pointer

class Pointer

A class that implements pointer-like behavior in Python.

value -> Any

Get the current value of the pointer.

get() Any

Dereference the pointer to access the value.

set(value: Any) None

Dereference the pointer and set the new value.

address() int

Return the ‘address’ of the pointer (its id).

point_to(other_pointer: Pointer) None

Point this pointer to the memory location of another pointer.

is_null() bool

Check if the pointer is null (points to None).

DeferredValue

class DeferredValue

A class that defers the evaluation of a value and provides a way to access the deferred value. The update interval is dynamically calculated based on CPU frequency.

set(value: Any) None

Sets the value to be deferred.

get() Any

Returns the deferred value.

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 Pointer and DeferredValue provide fine-grained control when needed.

  • Thread safety is ensured in relevant components through proper locking mechanisms.