Documentation Index
Fetch the complete documentation index at: https://mintlify.com/alex-ber/AlexBerUtils/llms.txt
Use this file to discover all available pages before exploring further.
Module-level types
FutureType
A type alias for values that can be awaited or used asconcurrent.futures.Future.
Thread-local helpers
threadlocal_var
Retrieves or lazily initialises a named attribute on athreading.local object.
The thread-local storage object to read from / write to.
The attribute name on
thread_locals.Zero-or-more-argument callable used to create the value when it does not exist yet.
Positional arguments forwarded to
factory.Keyword arguments forwarded to
factory.Any).
get_threadlocal_var
Retrieves a named attribute from athreading.local object, raising if it is not yet initialised.
The thread-local storage object.
The attribute name to retrieve.
Any).
Raises:
ValueError— if the attribute isNone(i.e. not initialised).
del_threadlocal_var
Deletes a named attribute from athreading.local object. Silently does nothing if the attribute does not exist.
The thread-local storage object.
The attribute name to delete.
None
Utility classes
RootMixin
A cooperative-multiple-inheritance root that terminates thesuper().__init__(**kwargs) delegation chain.
All locking mixin classes ultimately inherit from RootMixin, ensuring that **kwargs are absorbed without being forwarded to object.__init__.
validate_param
Asserts that a required parameter value is notNone.
The value to validate.
The human-readable name used in the error message.
None
Raises:
ValueError— ifparam_value is None.
RLock
A reentrant lock that supports both synchronous and asynchronous acquisition. Unlikethreading.RLock, this implementation also exposes coroutine-based acquire/release methods and full async with context-manager support, making it safe to share across sync threads and async tasks.
See the design article for details.
RLock.acquire
Acquires the synchronous (threading) lock, blocking until available. Reentrant — the owning thread may acquire again. Returns:True
RLock.release
Releases the synchronous lock held by the current thread. Returns:True
Raises:
RuntimeError— if the current thread does not own the lock.
RLock.async_acquire
Coroutine that acquires the asynchronous lock, suspending the current task until available. Reentrant — the owning task may acquire again. Returns:True
RLock.async_release
Coroutine that releases the asynchronous lock held by the current task. Returns:True
Raises:
RuntimeError— if the current asyncio task does not own the lock.
RLock.__enter__ / __exit__
Context manager protocol.__enter__ calls acquire(); __exit__ calls release().
RLock.__aenter__ / __aexit__
Async context manager protocol.__aenter__ awaits async_acquire(); __aexit__ awaits async_release().
Locking Mixin classes
All mixins accept**kwargs in __init__ and expect at minimum:
| kwarg | Type | Meaning |
|---|---|---|
obj | Any | The object being wrapped/proxied |
lock | RLock | The lock (some mixins auto-create one) |
LockingIterableMixin
Wraps__iter__ so that each call to __next__ on the resulting iterator holds the lock.
Returns a LockingIterator from __iter__.
LockingAsyncIterableMixin
Wraps__aiter__ so that each __anext__ call on the resulting async iterator holds the lock.
Returns a LockingAsyncIterator from __aiter__.
LockingAccessMixin
Overrides__getattr__ to wrap every method found on the underlying object in a synchronized (or async-synchronized) wrapper. Handles Pydantic models specially (_copy_and_set_values).
Inherits from LockingPedanticObjMixin.
LockingCallableMixin
Overrides__call__ to wrap the underlying callable in the lock. Detects coroutine functions automatically and applies async with self._lock in that case.
LockingGetItemMixin
Makes__getitem__ and __setitem__ on the underlying collection thread-safe.
LockingSetItemMixin
Makes only__setitem__ thread-safe (read-write asymmetry for performance-oriented cases).
SyncContextManagerMixin
Adds synchronous__enter__ / __exit__ that delegate to self._lock.acquire() / self._lock.release().
AsyncContextManagerMixin
Adds asynchronous__aenter__ / __aexit__ that delegate to self._lock.async_acquire() / self._lock.async_release().
LockingDefaultLockMixin
Creates a newRLock() when no lock kwarg is provided, then stores it as self._lock before delegating upward.
LockingBaseLanguageModelMixin
Registers the proxy’s concrete type as a virtual subclass oflangchain_core.language_models.BaseLanguageModel (when available), so isinstance checks pass transparently.
Requires obj kwarg. No-op if langchain_core is not installed.
LockingDefaultAndBaseLanguageModelMixin
CombinesLockingDefaultLockMixin and LockingBaseLanguageModelMixin: auto-creates a lock and registers as a BaseLanguageModel subtype.
LockingProxy
A ready-to-use thread-safe proxy that composes all locking mixins. MRO includes:LockingDefaultAndBaseLanguageModelMixin, LockingIterableMixin, LockingAsyncIterableMixin, LockingAccessMixin, LockingCallableMixin, LockingGetItemMixin, LockingSetItemMixin, SyncContextManagerMixin, AsyncContextManagerMixin.
See the design article for details.
The object to wrap.
The reentrant lock to use. Auto-created if omitted.
LockingProxy instance whose every operation is guarded by the lock.
Thread / event-loop utilities
is_running_in_main_thread
ReturnsTrue when called from the process’s main thread.
Returns: bool
lift_to_async
Calls an async function from synchronous code, preserving the currentcontextvars.Context.
The async function to execute. Positional-only.
Positional arguments forwarded to
afunc.Keyword arguments forwarded to
afunc.afunc (T).
Raises:
RuntimeError— if called from the main thread while an event loop is already running (would block the loop).
StopAsyncIterationraised insideafuncis automatically converted toRuntimeErrorto avoid hanging futures.
FutureWrapper
A thin proxy aroundasyncio.Future that tracks whether the result was explicitly consumed (awaited or retrieved via result() / exception()). Unconsumed exceptions are logged automatically.
The future to wrap.
FutureWrapper.__await__
Awaits the underlying future, marking it as consumed.FutureWrapper.result
Returns the future’s result, marking it as consumed. Raises: Whatever the underlying future raises.FutureWrapper.exception
Returns the future’s exception (orNone), marking it as consumed.
FutureWrapper.add_done_callback
Registers a done callback on the underlying future.The callback to invoke when the future completes.
FutureWrapper.done
ReturnsTrue if the underlying future is complete.
Returns: bool
check_and_log_exception
Inspects aFutureWrapper without consuming it. If the future is done but unconsumed and holds an exception, the exception is logged at ERROR level.
The wrapped future to inspect.
None
handle_future_exception
Schedules a delayed call tocheck_and_log_exception on the running event loop. Useful for fire-and-forget tasks where exceptions should still surface in logs.
The future to monitor.
Seconds to wait before checking the future.
None
ensure_thread_event_loop
Ensures the current (non-main) thread has an asyncio event loop attached. If none exists, a new one is created withasyncio.new_event_loop() and stored in thread-local storage.
Returns: None
exec_in_executor
Runs a sync or async function inside an executor while preserving the currentContextVar context.
The executor to use. If
None, falls back to the executor set in initConfig(), then to the asyncio default.The sync or async function to run.
Positional arguments for
func.Keyword arguments for
func.asyncio.Future[T] — wrapped in a FutureWrapper that logs unconsumed exceptions.
Must be called from within a running event loop (async context).
exec_in_executor_threading_future
Likeexec_in_executor, but returns a concurrent.futures.Future instead of an asyncio.Future. Useful when the caller is on a non-async thread.
The executor to use. Resolution order same as
exec_in_executor.The sync or async function to run.
Positional arguments for
func.Keyword arguments for
func.concurrent.futures.Future[T]
chain_future_results
Propagates the outcome (result or exception) fromsource_future to target_future. Works with any combination of asyncio.Future and concurrent.futures.Future.
Typically used as a done callback:
The completed future to read from.
The future to set the result/exception on.
None (no-op if target_future is already done).
get_main_event_loop
Returns the event loop stored byinitConfig(). Returns None if initConfig() was never called.
Returns: asyncio.AbstractEventLoop | None
AsyncExecutionQueue
An async-context-manager task queue that serialises task submission and executes each task in a given executor, preservingContextVar context.
Custom queue instance. A fresh
asyncio.Queue is created when omitted.Executor for task execution. Falls back to
initConfig() executor, then asyncio default.AsyncExecutionQueue.__aenter__ / __aexit__
Starts the backgroundworker task on enter; calls aclose() on exit.
AsyncExecutionQueue.worker
Coroutine. Continuously dequeues and executes tasks until a close sentinel is received. Each task is run viaexec_in_executor inside the stored context.
AsyncExecutionQueue.aadd_task
Asynchronously enqueues a callable for execution.The sync or async function to execute. Positional-only.
Positional arguments forwarded to
func.Keyword arguments forwarded to
func.asyncio.Future — resolves to the return value of func.
AsyncExecutionQueue.add_task
Synchronous variant ofaadd_task — submits the task from a non-async thread via exec_in_executor_threading_future.
Executor used to run the async submission itself.
The sync or async function to execute. Positional-only.
Positional arguments forwarded to
func.Keyword arguments forwarded to
func.concurrent.futures.Future
AsyncExecutionQueue.aclose
Cancels all pending tasks in the queue, then enqueues a close sentinel and awaits the worker coroutine. Returns:None (coroutine)
Context variable helpers
get_context_vars
Collects all top-levelContextVar instances from one or more modules and associates each with a factory callable. As a side effect, calls reset_context_vars on the collected entities.
One or more modules to scan.
Custom resolver: given a
ContextVar and its module, returns a factory callable. When None, looks up <var.name>_DEFAULT in the same module.List[Dict] — each dict has keys 'var' (ContextVar) and 'factory' (Callable).
reset_context_vars
Resets eachContextVar in entities to the value returned by its associated factory.
Dicts produced by
get_context_vars, each with 'var' and 'factory' keys.None
Raises:
ValueError— if a factory is not callable.
initConfig
Initialises global state required bylift_to_async(), exec_in_executor(), and get_main_event_loop(). Must be called from the main thread while an event loop is running.
Sets the global default executor. When
None, the asyncio default is used.None
Raises:
RuntimeError— if no event loop is currently running.
