Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/ismael-sarmiento/kimera_python/llms.txt

Use this file to discover all available pages before exploring further.

Python’s standard json.dumps rejects many common types — datetime, date, tuple, and nested combinations of these will raise a TypeError at runtime. KimeraSerializer solves this by routing each object through a prioritized chain of handler classes, each responsible for encoding and decoding one specific Python type into a JSON-safe envelope. The result is a fully round-trippable JSON string that can be stored in a cache, sent over a network, or written to a file and reconstructed back to the original Python object without any manual type hints.

KimeraSerializer

KimeraSerializer is a composed class that holds an ordered list of BaseSerializerHandler instances. When you call serialize, it finds the first handler whose can_i_handle_object_to_serialize returns True and delegates to that handler’s build_serializer. Deserialization follows the same pattern in reverse.

Supported Types

Primitives

str, int, float, and bool are handled by DefaultSerializerHandler.

Collections

list and tuple are handled element-by-element, preserving nesting.

Mappings

dict is handled key-by-key, with each value serialized recursively.

Date

datetime.date is serialized using the format %Y%m%d.

Datetime

datetime.datetime is serialized using %Y%m%d %H:%M:%S.%f.

Nested

Any combination of the above types nested arbitrarily deep.

Methods

Finds the first handler whose can_i_handle_object_to_serialize returns True and calls its build_serializer. Returns a JSON string envelope of the form {'data': ..., 'serializer': '<HandlerClassName>'}.
Reads the serializer field from a JSON envelope string to identify the correct handler, then calls build_deserializer to reconstruct the original Python object.
Filters the handler list for the first handler whose can_i_handle_object_to_serialize returns True for the given object and returns that handler instance. Raises an Exception if no handler is found.
Filters the handler list for the first handler whose can_i_handle_object_to_deserialize returns True for the given serialized string and returns that handler instance. Raises an Exception if no handler is found.
Returns True if any handler except DefaultSerializerHandler (the last entry) can handle the object for serialization. Used by KimeraEncoder.default to decide whether to delegate to KimeraSerializer or fall back to the standard encoder.

Full Round-Trip Example

from components.tools.serializers.custom import KimeraSerializer
from datetime import datetime, date

s = KimeraSerializer()

# Complex nested object
obj = {
    'created': datetime(2024, 1, 15, 12, 0, 0),
    'birthday': date(1990, 6, 20),
    'scores': [95, 87, (100, 99)],
    'meta': {'active': True, 'tags': ['a', 'b']}
}

serialized = s.serialize(obj)
restored = s.deserialize(serialized)
assert restored == obj
print(restored['created'])  # datetime(2024, 1, 15, 12, 0, 0)
Custom user-defined class instances that are not in the handler list will fall through to DefaultSerializerHandler, which passes the object to the standard json.JSONEncoder. If the encoder cannot handle the type, a TypeError is raised. Extend BaseSerializerHandler and add your handler to a custom KimeraSerializer subclass to support additional types.

Handler Chain

KimeraSerializer.__init__ builds the following ordered list. The first handler whose can_i_handle_object_to_serialize(obj) returns True is used:
1

DateSerializerHandler

Matches datetime.date objects where type(obj) == date exactly (not datetime subclass). Encodes using %Y%m%d; decodes back to date.
2

DateTimeSerializerHandler

Matches datetime.datetime instances (isinstance(obj, datetime)). Encodes using %Y%m%d %H:%M:%S.%f; decodes back to datetime.
3

DictSerializerHandler

Matches any dict. Each value is recursively serialized by calling KimeraSerializer().serialize(value).
4

TupleSerializerHandler

Matches any tuple. Each element is recursively serialized; deserialization reconstructs a tuple.
5

ListSerializerHandler

Matches any list. Each element is recursively serialized; deserialization reconstructs a list.
6

DefaultSerializerHandler

Catch-all — can_i_handle_object_to_serialize always returns True. Delegates to KimeraEncoder / KimeraDecoder for final JSON encoding.
DateSerializerHandler appears before DateTimeSerializerHandler in the chain. DateSerializerHandler uses an exact class check (obj.__class__ == date) so it will never match a datetime instance. DateTimeSerializerHandler uses isinstance(obj, datetime), which would also match a plain date if it were placed first — so the ordering preserves correct round-trip behaviour for both types.

KimeraEncoder / KimeraDecoder

KimeraEncoder and KimeraDecoder are json.JSONEncoder / json.JSONDecoder subclasses that integrate directly with Python’s standard json module. Use them when you already have code using json.dumps / json.loads and want Kimera’s type support with minimal refactoring.

How They Work

  • KimeraEncoder.default(_object) — called by json.dumps for any object it cannot natively serialize. It delegates to KimeraSerializer if a non-default handler can process the object; otherwise it falls back to super().default().
  • KimeraDecoder.object_hook(_object) — called by json.loads for every decoded JSON object (dict). If the dict looks like a Kimera envelope ({'serializer': ..., 'data': ...}), it reconstructs the original Python type via KimeraSerializer().deserialize.

Example

import json
from components.tools.serializers.custom import KimeraEncoder, KimeraDecoder
from datetime import datetime

data = {'ts': datetime.now()}
encoded = json.dumps(data, cls=KimeraEncoder)
decoded = json.loads(encoded, cls=KimeraDecoder)

Pickle Serializer

The Pickle class is a thin, stateless wrapper around Python’s built-in pickle module that provides a consistent method-naming convention matching the rest of Kimera’s serializer API.

Methods

Calls pickle.dumps(_object) and returns the binary byte string representation of the Python object.
Calls pickle.loads(serializer_object) and reconstructs the original Python object from its binary representation.

Example

from components.tools.serializers._pickle import Pickle
from datetime import datetime

obj = {'ts': datetime.now(), 'values': [1, 2, 3]}
binary = Pickle.serializer(obj)
restored = Pickle.deserializer(binary)
assert restored == obj
Never deserialize Pickle data received from an untrusted source. The pickle format can execute arbitrary code during deserialization, making it a serious security risk for data that crosses network or trust boundaries. Use KimeraSerializer (JSON-based) for any data exchanged between services or stored externally.

Build docs developers (and LLMs) love