HookManager#
- class brainstate.HookManager(config=None)[source]#
Manager for hooks on a single State instance.
This class handles registration, unregistration, and execution of hooks for all hook types (read, write_before, write_after, restore).
- Features:
Priority-based execution ordering
Thread-safe hook registration and execution
Hook list caching for performance
Sequential chaining for write_before hooks
Configurable error handling
- Thread Safety:
All operations are protected by a reentrant lock (RLock), allowing hooks to safely trigger other state operations.
Examples
>>> from brainstate import HookManager >>> manager = HookManager() >>> handle = manager.register_hook('read', lambda ctx: print(ctx.value), priority=10) >>> manager.has_hooks('read') True >>> handle.disable() >>> manager.clear_hooks()
- execute_write_before_hooks(new_value, old_value, state_ref)[source]#
Execute all write_before hooks with sequential chaining.
Each hook can transform the value, and the next hook receives the transformed output.
- Parameters:
- Return type:
- Raises:
HookCancellationError – If a hook cancels the operation
- register_hook(hook_type, callback, priority=0, name=None, enabled=True)[source]#
Register a new hook.
- Parameters:
hook_type (
Literal['read','write_before','write_after','restore','init']) – Type of hook to registercallback (
Callable[[HookContext],Any]) – Callable that receives a HookContextpriority (
int) – Execution priority (higher = earlier, default 0)enabled (
bool) – Whether the hook is enabled initially (default True)
- Return type:
- Raises:
HookRegistrationError – If hook_type is invalid
Examples
>>> def my_hook(ctx): ... print(f"Hook called: {ctx.operation}") >>> handle = manager.register_hook('read', my_hook, priority=10, name='my_reader')
- unregister_hook(handle)[source]#
Unregister a hook using its handle.
- Parameters:
handle (
HookHandle) – The HookHandle to unregister- Return type: