4.3. Context#

4.3.1. Context classes#

class caterpillar.context.Context[source]#

Represents a context object with attribute-style access.

Represents the primary container for context-aware operations during packing and unpacking. It manages attribute access, supports hierarchical relationships, and tracks contextual state. Conforms to the _ContextLike protocol.

__context_getattr__(path: str) Any[source]#

Retrieves an attribute from the context.

Parameters:

key – The attribute key.

Returns:

The value associated with the key.

class caterpillar.context.ContextPath(path: str | None = None)[source]#

Represents a lambda function for retrieving a value from a Context based on a specified path.

__call__(context: _ContextLike) _T[source]#

Calls the lambda function to retrieve a value from a Context.

Parameters:
  • context – The Context from which to retrieve the value.

  • kwds – Additional keyword arguments.

Returns:

The value retrieved from the Context based on the path.

__getattribute__(key: Literal['_field']) ContextPath['Field[_IT, _OT] | None'][source]#
__getattribute__(key: Literal['_parent']) ContextPath[_ContextLike]
__getattribute__(key: Literal['_obj']) ContextPath[_ContextLike]
__getattribute__(key: Literal['_offsets']) ContextPath[dict[int, Buffer]]
__getattribute__(key: Literal['_io']) ContextPath[IOBase]
__getattribute__(key: Literal['_pos']) ContextPath[int]
__getattribute__(key: Literal['_index']) ContextPath[int]
__getattribute__(key: Literal['_path']) ContextPath[str]
__getattribute__(key: Literal['_is_seq']) ContextPath[bool]
__getattribute__(key: Literal['_root']) ContextPath[_ContextLike]
__getattribute__(key: Literal['_order']) ContextPath[_EndianLike]
__getattribute__(key: Literal['_arch']) ContextPath[_ArchLike]
__getattribute__(key: str) ContextPath[_IT]

Gets an attribute from the ContextPath, creating a new instance if needed.

Parameters:

key – The attribute key.

Returns:

A new ContextPath instance with an updated path.

__repr__() str[source]#

Returns a string representation of the ContextPath.

Returns:

A string representation.

property parentctx: ContextPath[_ContextLike]#

Added in version 2.8.0.

class caterpillar.context.ContextLength(path: ContextPath[Sized])[source]#

Encapsulates length information derived from the context, often used in size-dependent field evaluation.

class caterpillar.context.ConditionContext(condition: _ContextLambda[bool], depth: int = 2)[source]#

Class implementation of an inline condition.

Use this class to automatically apply a condition to multiple field definitions. Note that this class will only work if it has access to the parent stack frame.

@struct
class Format:
    magic: b"MGK"
    length: uint32

    with this.length > 32:
        # other field definitions here
        foo: uint8

This class will replace any existing fields!

Parameters:

condition (Union[_ContextLambda, bool]) – a context lambda or constant boolean value

class caterpillar.context.SetContextVar(key: str, func: _ContextLambda[_IT])[source]#

Defines an action that sets a context variable during pack or unpack.

The value assigned to the context key is computed dynamically using a user-provided callable evaluated at runtime.

Parameters:
  • key (str) – Name of the context variable to set

  • func (callable) – Callable used to compute the context value

__action_pack__(context: _ContextLike) None[source]#

Apply the context variable assignment during packing.

The callable is evaluated and its result is stored in the context under the configured key.

Parameters:

context (object) – Active packing context

Returns:

None

Return type:

None

__action_unpack__(context: _ContextLike) None[source]#

Apply the context variable assignment during unpacking.

The callable is evaluated and its result is stored in the context under the configured key.

Parameters:

context (object) – Active unpacking context

Returns:

None

Return type:

None

4.3.2. Extra options#

context.O_CONTEXT_FACTORY: Flag[_ContextFactoryLike] = Flag(name='option.context_factory', value=<class 'caterpillar.context.Context'>)#

Defines the default factory used to instantiate context objects during the packing and unpacking process. To use the C-extension Context implementation for a 10% speed caveat, use:

from caterpillar.context import O_CONTEXT_FACTORY
from caterpillar.c import c_Context

# that's all you have to do
O_CONTEXT_FACTORY.value = c_Context

Added in version 2.6.0.

4.3.3. Special paths#

caterpillar.context.this: Final[ContextPath[_ContextLike]] = Path('_obj')#

Context path pointing to the current object in the evaluation context.

This context path is used to reference the active object being processed when navigating or resolving nested structures using context paths.

caterpillar.context.ctx: Final[ContextPath[_ContextLike]] = Path(None)#

Context path pointing to the current evaluation context.

This context path allows access to the full context dictionary rather than a specific object within it.

caterpillar.context.parent: Final[ContextPath[_ContextLike]] = Path('_parent._obj')#

Context path pointing to the parent object’s current object.

This context path is used to reference the object belonging to the parent context level when navigating nested context structures.

caterpillar.context.parentctx: Final[ContextPath[_ContextLike]] = Path('_parent')#

Context path pointing to the parent evaluation context.

This context path allows access to the full parent context dictionary rather than only its object.

Added in version 2.8.0.

caterpillar.context.root: Final[ContextPath[_ContextLike]] = Path('_root')#

Context path pointing to the root evaluation context.

This context path is used to reference the top-level context in a nested context hierarchy.

Added in version 2.6.0.

4.3.4. Special Attributes#

context.CTX_PARENT = '_parent'#

Identifies the parent object within the context tree.

context.CTX_OBJECT = '_obj'#

Refers to the current object associated with the context.

context.CTX_OFFSETS = '_offsets'#

Stores offset information used during stream parsing or generation.

context.CTX_STREAM = '_io'#

References the data stream associated with the packing or unpacking operation.

context.CTX_FIELD = '_field'#

Indicates the current field being processed within the structure.

context.CTX_VALUE = '_value'#

Stores the value associated with the current context node.

context.CTX_POS = '_pos'#

Represents the current position within the stream or structure.

context.CTX_INDEX = '_index'#

Maintains the index for sequence or array-based context elements.

context.CTX_PATH = '_path'#

Provides the full path to the current context object.

context.CTX_SEQ = '_is_seq'#

Holds a reference to the sequence object, if applicable.

context.CTX_ROOT = '_root'#

Points to the root of the entire context hierarchy.

context.CTX_ORDER = '_order'#

Stores the currently used endianess (only in root context).

Added in version 2.7.0.

context.CTX_ARCH = '_arch'#

Stores the currently used architecture (only in root context).

Added in version 2.7.0.

4.3.5. Expressions#

class caterpillar.context.ExprMixin[source]#

A mixin class providing methods for creating binary and unary expressions.

class caterpillar.context.BinaryExpression(operand: Callable[[Any, Any], bool], left: Any | _ContextLambda[Any], right: Any | _ContextLambda[Any])[source]#

Represents a binary expression.

Parameters:
  • operand – The binary operator function.

  • left – The left operand.

  • right – The right operand.

class caterpillar.context.UnaryExpression(name: str, operand: Callable[[Any], Any], value: Any | _ContextLambda[Any])[source]#

Represents a unary expression.

Parameters:
  • name – The name of the unary operator.

  • operand – The unary operator function.

  • value – The operand.