MutableWriteHookContext#
- class brainstate.MutableWriteHookContext(operation, state_ref, timestamp=time(), metadata=dict(), value=None, old_value=None, transformed_value=None, cancel=False, cancel_reason=None)[source]#
Context for write_before hooks with transformation capabilities.
This context allows hooks to transform the value being written or cancel the write operation entirely. Hooks execute in priority order, and each hook receives the transformed output from the previous hook (sequential chaining).
Examples
>>> def clip_values(ctx: MutableWriteHookContext): ... # Transform the value by clipping to [-1, 1] ... import jax.numpy as jnp ... input_value = ctx.transformed_value if ctx.transformed_value is not None else ctx.value ... ctx.transformed_value = jnp.clip(input_value, -1.0, 1.0)
>>> def validate_positive(ctx: MutableWriteHookContext): ... # Cancel if value is negative ... import jax.numpy as jnp ... check_value = ctx.transformed_value if ctx.transformed_value is not None else ctx.value ... if jnp.any(check_value < 0): ... ctx.cancel = True ... ctx.cancel_reason = "Value must be positive"