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: object

A 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:

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

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:
  • 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

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]

class serilux.SerializableRegistry[source]

Bases: object

Registry for serializable classes to facilitate class lookup and instantiation.

classmethod clear_registry()[source]

Clear the registry. Useful for testing.

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:
  • 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.

registry = {}
class serilux.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.

clear()[source]

Clear all registered objects.

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

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

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_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.

register_many(objects)[source]

Register multiple objects from a dictionary.

Parameters:

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

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:

Dict[str, Any] | None

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:

Dict[str, Any] | None

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:
  • 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.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.SeriluxError[source]

Bases: Exception

Base exception for all Serilux errors.

exception serilux.SerializationError(message, obj_type=None, field=None)[source]

Bases: SeriluxError

Exception raised when serialization fails.

__init__(message, obj_type=None, field=None)[source]

Initialize a SerializationError.

Parameters:
  • message (str) – Error message

  • obj_type (str) – Type of object being serialized (optional)

  • field (str) – Field that caused the error (optional)

exception serilux.DeserializationError(message, obj_type=None, field=None)[source]

Bases: SeriluxError

Exception raised when deserialization fails.

__init__(message, obj_type=None, field=None)[source]

Initialize a DeserializationError.

Parameters:
  • message (str) – Error message

  • obj_type (str) – Type of object being deserialized (optional)

  • field (str) – Field that caused the error (optional)

exception serilux.ClassNotFoundError(class_name)[source]

Bases: DeserializationError

Exception raised when a class is not found in the registry.

__init__(class_name)[source]

Initialize a ClassNotFoundError.

Parameters:

class_name (str) – Name of the class that was not found

exception serilux.ValidationError(message, obj=None)[source]

Bases: SeriluxError

Exception raised when validation fails.

__init__(message, obj=None)[source]

Initialize a ValidationError.

Parameters:
  • message (str) – Error message

  • obj – Object that failed validation (optional)

exception serilux.CircularReferenceError(message='Circular reference detected')[source]

Bases: SerializationError

Exception raised when a circular reference is detected.

__init__(message='Circular reference detected')[source]

Initialize a CircularReferenceError.

Parameters:

message (str) – Error message

exception serilux.DepthLimitError(max_depth, current_depth=None)[source]

Bases: SerializationError

Exception raised when serialization depth limit is exceeded.

__init__(max_depth, current_depth=None)[source]

Initialize a DepthLimitError.

Parameters:
  • max_depth (int) – Maximum allowed depth

  • current_depth (int) – Current depth when error occurred (optional)

exception serilux.CallableError(message, callable_type=None)[source]

Bases: SeriluxError

Exception raised when callable serialization/deserialization fails.

__init__(message, callable_type=None)[source]

Initialize a CallableError.

Parameters:
  • message (str) – Error message

  • callable_type (str) – Type of callable (function/method/builtin/lambda)

exception serilux.InvalidFieldError(field_name, reason=None)[source]

Bases: SerializationError

Exception raised when an invalid field is encountered.

__init__(field_name, reason=None)[source]

Initialize an InvalidFieldError.

Parameters:
  • field_name (str) – Name of the invalid field

  • reason (str) – Reason why the field is invalid (optional)

exception serilux.UnknownFieldError(field_name, obj_type)[source]

Bases: DeserializationError

Exception raised when an unknown field is encountered during deserialization.

__init__(field_name, obj_type)[source]

Initialize an UnknownFieldError.

Parameters:
  • field_name (str) – Name of the unknown field

  • obj_type (str) – Type of object being deserialized