Serializable Module¶
Core Classes¶
- class serilux.serializable.Serializable[source]¶
Bases:
objectA base class for objects that can be serialized and deserialized.
- add_serializable_fields(fields)[source]¶
Add field names to the list that should be included in serialization.
- Parameters:
- Raises:
InvalidFieldError – If any provided field is not a string.
- remove_serializable_fields(fields)[source]¶
Remove field names from the list that should be included in serialization.
- serialize(max_depth=100, _current_depth=0)[source]¶
Serialize the object to a dictionary.
Automatically handles: - Serializable objects - Lists and dicts containing Serializable objects - Callable objects (functions, methods, builtins) - Lists and dicts containing callable objects
- Parameters:
- Returns:
Dictionary containing all serializable fields.
- Raises:
DepthLimitError – If nesting depth exceeds max_depth.
- Return type:
- deserialize(data, strict=False, registry=None)[source]¶
Deserialize the object from a dictionary, restoring its state.
Automatically handles: - Serializable objects - Lists and dicts containing Serializable objects (with two-phase deserialization) - Callable objects (functions, methods, builtins) - Lists and dicts containing callable objects - Automatic ObjectRegistry creation and propagation for callable deserialization
- Parameters:
- Raises:
ValueError – If strict=True and unknown field is found, or if deserialization fails.
- class serilux.serializable.SerializableRegistry[source]¶
Bases:
objectRegistry for serializable classes to facilitate class lookup and instantiation.
- registry = {}¶
- classmethod register_class(class_name, class_ref)[source]¶
Register a class for serialization purposes by adding it to the registry.
- Parameters:
- Raises:
ValueError – If a different class with the same name is already registered. This prevents class name conflicts that could lead to incorrect deserialization.
- class serilux.serializable.ObjectRegistry[source]¶
Bases:
objectGeneric registry for looking up objects by ID and class name.
This registry allows deserialization to find objects by their ID without hardcoding specific object types (like “routines”). It supports multiple lookup strategies: - By ID: Find object with matching _id attribute - By class name: Find objects of a specific class - Custom lookup: Register custom lookup functions
For detailed information about ObjectRegistry design, principles, and usage patterns, see the ObjectRegistry: Design and Implementation guide.
Decorators¶
- serilux.serializable.register_serializable(cls)[source]¶
Decorator to register a class as serializable in the registry.
This decorator ensures that the class can be instantiated without arguments, which is required for proper deserialization. It validates that __init__ either accepts no parameters (except self) or all parameters have default values.
- Parameters:
cls – Class to be registered.
- Returns:
The same class with registration completed.
- Raises:
TypeError – If the class cannot be initialized without arguments. This happens when __init__ has required parameters (without defaults) other than ‘self’. For Serializable subclasses, use configuration dictionary instead of constructor parameters.
ValueError – If a different class with the same name is already registered. This prevents class name conflicts that could lead to incorrect deserialization.
Note
For Serializable subclasses, all configuration should be stored in configuration attributes and set after object creation, not passed as constructor parameters. This ensures proper serialization/deserialization support.
Validation Functions¶
- serilux.serializable.check_serializable_constructability(obj)[source]¶
Check if a Serializable object can be constructed without arguments.
This function validates that the object’s class can be instantiated without arguments, which is required for proper deserialization.
- Parameters:
obj (Serializable) – Serializable object to check.
- Raises:
TypeError – If the object’s class cannot be initialized without arguments. This includes detailed information about which class failed and what parameters are required.
- serilux.serializable.validate_serializable_tree(obj, visited=None)[source]¶
Recursively validate that all Serializable objects in a tree can be constructed.
This function traverses all Serializable objects referenced by the given object and checks that each one can be instantiated without arguments. This is useful for validating a Serializable object tree before serialization to catch issues early.
- Parameters:
obj (Serializable) – Root Serializable object to validate.
visited (set | None) – Set of object IDs already visited (to avoid infinite loops).
- Raises:
TypeError – If any Serializable object in the tree cannot be constructed without arguments. The error message includes the path to the problematic object.
Callable Serialization Functions¶
- serilux.serializable.serialize_callable(callable_obj, owner=None)[source]¶
Serialize a callable object (function or method).
- Parameters:
callable_obj (Callable | None) – Callable object to serialize.
owner (Any | None) – Optional object that owns this callable. If provided and callable_obj is a method, validates that the method belongs to this owner object. This ensures that only methods of the serialized object itself can be serialized, which is required for cross-process deserialization.
- Returns:
Serialized dictionary, or None if serialization is not possible or validation fails.
- Raises:
ValueError – If owner is provided and callable_obj is a method that doesn’t belong to the owner object.
- Return type:
- serilux.serializable.serialize_callable_with_fallback(callable_obj, owner=None, fallback_to_expression=True)[source]¶
Serialize a callable object with automatic fallback to expression extraction.
This function tries standard serialization first (for module functions, methods, builtins). If that fails and fallback_to_expression is True, it attempts to extract the source code and serialize as lambda_expression.
- Parameters:
callable_obj (Callable | None) – Callable object to serialize.
owner (Any | None) – Optional object that owns this callable. If provided and callable_obj is a method, validates that the method belongs to this owner object.
fallback_to_expression (bool) – If True, attempt to extract source code as lambda_expression when standard serialization fails or function is not accessible from module level.
- Returns:
Serialized dictionary, or None if serialization is not possible.
- Raises:
ValueError – If serialization fails and fallback also fails, with detailed error message.
- Return type:
- serilux.serializable.deserialize_callable(callable_data, registry=None, context=None)[source]¶
Deserialize a callable object using a generic object registry.
- Parameters:
callable_data (Dict[str, Any] | None) – Serialized callable object data.
registry (ObjectRegistry | None) – Optional ObjectRegistry for looking up objects by ID. If provided, uses this registry to find method owners.
context (Dict[str, Any] | None) – Optional context dictionary for backward compatibility. If registry is not provided, falls back to context-based lookup. Context can contain: - “routines”: Dict mapping IDs to Routine objects (legacy support) - “registry”: ObjectRegistry instance - Any other object collections
- Returns:
Callable object, or None if deserialization is not possible.
- Return type:
Callable | None
- serilux.serializable.deserialize_lambda_expression(expression_data, default_param_name='data')[source]¶
Deserialize a lambda expression from serialized data.
- Parameters:
- Returns:
Callable lambda function, or None if deserialization fails.
- Raises:
ValueError – If deserialization fails with detailed error message.
- Return type:
Callable | None
- serilux.serializable.extract_callable_expression(source)[source]¶
Extract lambda expression or function body from source code.
This function can extract expressions from both lambda functions and regular function definitions, making them suitable for serialization as lambda_expression.
- Parameters:
source (str) – Source code string (e.g., “f = lambda x: x.get(‘priority’) == ‘high’” or “def test_lambda(x):
return x.get(‘priority’) == ‘high’”).
- Returns:
Expression string (e.g., “x.get(‘priority’) == ‘high’”), or None if extraction fails.
- Return type:
str | None