Serializable Module

Core Classes

class serilux.serializable.Serializable[source]

Bases: object

A base class for objects that can be serialized and deserialized.

__init__()[source]

Initialize a serializable object with no specific fields.

add_serializable_fields(fields)[source]

Add field names to the list that should be included in serialization.

Parameters:

fields (List[str]) – List of field names to be serialized.

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.

Parameters:

fields (List[str]) – List of field names to be removed.

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:
  • max_depth (int) – Maximum nesting depth to prevent stack overflow (default: 100).

  • _current_depth (int) – Current depth (used internally, do not set).

Returns:

Dictionary containing all serializable fields.

Raises:

DepthLimitError – If nesting depth exceeds max_depth.

Return type:

Dict[str, Any]

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:
  • data (Dict[str, Any]) – Dictionary containing all serializable fields.

  • strict (bool) – If True, raise error for unknown fields. If False, ignore them (default).

  • registry (Any | None) – Optional ObjectRegistry for deserializing callables. If None, creates a new registry automatically.

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.

Parameters:
  • item (Any) – Item to deserialize (can be dict, list, or primitive type).

  • registry (Any | None) – Optional ObjectRegistry for deserializing callables.

Returns:

Deserialized item.

Return type:

Any

class serilux.serializable.SerializableRegistry[source]

Bases: object

Registry 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:
  • class_name (str) – The name of the class to register.

  • class_ref (type) – A reference to the class being registered.

Raises:

ValueError – If a different class with the same name is already registered. This prevents class name conflicts that could lead to incorrect deserialization.

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.

class serilux.serializable.ObjectRegistry[source]

Bases: object

Generic 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

__init__()[source]

Initialize an empty registry.

register(obj, object_id=None)[source]

Register an object in the registry.

Parameters:
  • obj (Any) – Object to register.

  • object_id (str | None) – Optional ID to use. If None, uses obj._id if available.

register_many(objects)[source]

Register multiple objects from a dictionary.

Parameters:

objects (Dict[str, Any]) – Dictionary mapping IDs to objects.

find_by_id(object_id)[source]

Find an object by its ID.

Parameters:

object_id (str) – Object ID to look up.

Returns:

Object if found, None otherwise.

Return type:

Any | None

find_by_class_and_id(class_name, object_id)[source]

Find an object by class name and ID.

Parameters:
  • class_name (str) – Class name to filter by.

  • object_id (str) – Object ID to look up.

Returns:

Object if found, None otherwise.

Return type:

Any | None

register_custom_lookup(class_name, lookup_func)[source]

Register a custom lookup function for a specific class.

Parameters:
  • class_name (str) – Class name to register lookup for.

  • lookup_func (Callable[[str, str], Any | None]) – Function that takes (class_name, object_id) and returns object or None.

clear()[source]

Clear all registered objects.

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:

Dict[str, Any] | None

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:

Dict[str, Any] | None

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:
  • expression_data (Dict[str, Any]) – Dictionary containing “_type”: “lambda_expression” and “expression”.

  • default_param_name (str) – Default parameter name for the lambda (default: “data”).

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