API Reference¶
This section contains the complete API reference for Serilux.
Core Classes¶
Functions¶
Serilux - A powerful serialization framework for Python objects
Provides flexible serialization and deserialization capabilities with automatic type registration and validation.
- class serilux.Serializable[source]¶
Bases:
objectA base class for objects that can be serialized and deserialized.
- __init__()[source]¶
Initialize a serializable object.
Automatically populates fields_to_serialize using discovered fields if the class was registered with @register_serializable.
- 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.
- 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.
- static deserialize_item(item, registry=None)[source]¶
Deserialize an item (dict, list, or primitive type).
Automatically handles callable deserialization.
- 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:
- class serilux.SerializableRegistry[source]¶
Bases:
objectRegistry for serializable classes to facilitate class lookup and instantiation.
- classmethod get_class(class_name)[source]¶
Retrieve a class reference from the registry by its name.
- Parameters:
class_name (str) – The name of the class to retrieve.
- Returns:
The class reference if found, None otherwise.
- 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.
- registry = {}¶
- class serilux.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
- serilux.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.
It also performs automatic field discovery for fields with type hints and dataclass fields.
- Parameters:
cls – Class to be registered.
- Returns:
The same class with registration completed and field discovery info attached.
- Raises:
TypeError – If the class cannot be initialized without arguments.
ValueError – If a different class with the same name is already registered.
- serilux.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.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.
- serilux.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.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.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.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.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
- exception serilux.SerializationError(message, obj_type=None, field=None)[source]¶
Bases:
SeriluxErrorException raised when serialization fails.
- exception serilux.DeserializationError(message, obj_type=None, field=None)[source]¶
Bases:
SeriluxErrorException raised when deserialization fails.
- exception serilux.ClassNotFoundError(class_name)[source]¶
Bases:
DeserializationErrorException raised when a class is not found in the registry.
- exception serilux.ValidationError(message, obj=None)[source]¶
Bases:
SeriluxErrorException raised when validation fails.
- exception serilux.CircularReferenceError(message='Circular reference detected')[source]¶
Bases:
SerializationErrorException raised when a circular reference is detected.
- exception serilux.DepthLimitError(max_depth, current_depth=None)[source]¶
Bases:
SerializationErrorException raised when serialization depth limit is exceeded.
- exception serilux.CallableError(message, callable_type=None)[source]¶
Bases:
SeriluxErrorException raised when callable serialization/deserialization fails.
- exception serilux.InvalidFieldError(field_name, reason=None)[source]¶
Bases:
SerializationErrorException raised when an invalid field is encountered.
- exception serilux.UnknownFieldError(field_name, obj_type)[source]¶
Bases:
DeserializationErrorException raised when an unknown field is encountered during deserialization.