Skip to content

confingy.serde#

serde #

SerializationKeys #

Constants for serialization markers in the serialized data.

Source code in src/confingy/serde.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
class SerializationKeys:
    """Constants for serialization markers in the serialized data."""

    CLASS = "_confingy_class"
    MODULE = "_confingy_module"
    LAZY = "_confingy_lazy"
    CONFIG = "_confingy_config"
    INIT = "_confingy_init"
    DATACLASS = "_confingy_dataclass"
    FIELDS = "_confingy_fields"
    CALLABLE = "_confingy_callable"
    TRACKED_INFO = "_confingy_tracked_info"
    UNSERIALIZABLE = "_confingy_unserializable"
    OBJECT = "_confingy_object"
    METHOD = "_confingy_method"
    NAME = "_confingy_name"
    CLASS_HASH = "_confingy_class_hash"
    ENUM = "_confingy_enum"
    TUPLE = "_confingy_tuple"
    SET = "_confingy_set"
    ITEMS = "_confingy_items"

SerializationHandler #

Bases: ABC

Abstract base class for serialization handlers.

Source code in src/confingy/serde.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
class SerializationHandler(ABC):
    """Abstract base class for serialization handlers."""

    @abstractmethod
    def can_handle(self, obj: Any) -> bool:
        """Check if this handler can serialize the given object."""
        pass

    @abstractmethod
    def serialize(self, obj: Any, context: "SerializationContext") -> Any:
        """Serialize the object."""
        pass

    @abstractmethod
    def deserialize(self, data: Any, context: "DeserializationContext") -> Any:
        """Deserialize the data."""
        pass

    def map_children(self, obj: Any, fn: "Callable[[Any], Any]") -> Any:
        """Apply fn to all child values, returning new object with transformed children.

        This enables recursive traversal of nested structures for operations like
        lens/unlens without duplicating container-specific logic.

        Default returns obj unchanged (for leaf types like primitives).
        """
        return obj

can_handle abstractmethod #

can_handle(obj: Any) -> bool

Check if this handler can serialize the given object.

Source code in src/confingy/serde.py
117
118
119
120
@abstractmethod
def can_handle(self, obj: Any) -> bool:
    """Check if this handler can serialize the given object."""
    pass

serialize abstractmethod #

serialize(obj: Any, context: SerializationContext) -> Any

Serialize the object.

Source code in src/confingy/serde.py
122
123
124
125
@abstractmethod
def serialize(self, obj: Any, context: "SerializationContext") -> Any:
    """Serialize the object."""
    pass

deserialize abstractmethod #

deserialize(
    data: Any, context: DeserializationContext
) -> Any

Deserialize the data.

Source code in src/confingy/serde.py
127
128
129
130
@abstractmethod
def deserialize(self, data: Any, context: "DeserializationContext") -> Any:
    """Deserialize the data."""
    pass

map_children #

map_children(obj: Any, fn: Callable[[Any], Any]) -> Any

Apply fn to all child values, returning new object with transformed children.

This enables recursive traversal of nested structures for operations like lens/unlens without duplicating container-specific logic.

Default returns obj unchanged (for leaf types like primitives).

Source code in src/confingy/serde.py
132
133
134
135
136
137
138
139
140
def map_children(self, obj: Any, fn: "Callable[[Any], Any]") -> Any:
    """Apply fn to all child values, returning new object with transformed children.

    This enables recursive traversal of nested structures for operations like
    lens/unlens without duplicating container-specific logic.

    Default returns obj unchanged (for leaf types like primitives).
    """
    return obj

SerializationContext #

Context for serialization operations.

Source code in src/confingy/serde.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
class SerializationContext:
    """Context for serialization operations."""

    def __init__(self):
        self.handlers: list[SerializationHandler] = []
        self._depth = 0
        self._max_depth = 100
        self._path: list[str] = []  # Track object path for debugging

    def register_handler(self, handler: SerializationHandler):
        """Register a serialization handler."""
        self.handlers.append(handler)

    def serialize(self, obj: Any, key: str | None = None) -> Any:
        """Serialize an object using registered handlers."""
        if key:
            self._path.append(key)

        self._depth += 1
        try:
            if self._depth > self._max_depth:
                path_str = " -> ".join(self._path)
                raise SerializationError(
                    f"Maximum recursion depth ({self._max_depth}) exceeded at path: {path_str}"
                )

            for handler in self.handlers:
                if handler.can_handle(obj):
                    return handler.serialize(obj, self)

            # Raise an error for unserializable objects
            path_str = " -> ".join(self._path) if self._path else "root"
            raise SerializationError(
                f"No handler found for type {type(obj).__name__} at path {path_str}"
            )
        except Exception as e:
            if not isinstance(e, SerializationError):
                path_str = " -> ".join(self._path) if self._path else "root"
                raise SerializationError(
                    f"Failed to serialize at path {path_str}: {e}"
                ) from e
            raise
        finally:
            self._depth -= 1
            if key:
                self._path.pop()

register_handler #

register_handler(handler: SerializationHandler)

Register a serialization handler.

Source code in src/confingy/serde.py
152
153
154
def register_handler(self, handler: SerializationHandler):
    """Register a serialization handler."""
    self.handlers.append(handler)

serialize #

serialize(obj: Any, key: str | None = None) -> Any

Serialize an object using registered handlers.

Source code in src/confingy/serde.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
def serialize(self, obj: Any, key: str | None = None) -> Any:
    """Serialize an object using registered handlers."""
    if key:
        self._path.append(key)

    self._depth += 1
    try:
        if self._depth > self._max_depth:
            path_str = " -> ".join(self._path)
            raise SerializationError(
                f"Maximum recursion depth ({self._max_depth}) exceeded at path: {path_str}"
            )

        for handler in self.handlers:
            if handler.can_handle(obj):
                return handler.serialize(obj, self)

        # Raise an error for unserializable objects
        path_str = " -> ".join(self._path) if self._path else "root"
        raise SerializationError(
            f"No handler found for type {type(obj).__name__} at path {path_str}"
        )
    except Exception as e:
        if not isinstance(e, SerializationError):
            path_str = " -> ".join(self._path) if self._path else "root"
            raise SerializationError(
                f"Failed to serialize at path {path_str}: {e}"
            ) from e
        raise
    finally:
        self._depth -= 1
        if key:
            self._path.pop()

DeserializationContext #

Context for deserialization operations.

Source code in src/confingy/serde.py
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
class DeserializationContext:
    """Context for deserialization operations."""

    def __init__(self, strict: bool = True):
        """Initialize deserialization context.

        Args:
            strict: If True (default), raise an error when serialized configs contain
                kwargs that no longer exist in the class signature. If False, emit
                a warning and ignore the extra kwargs. Similar to PyTorch's
                load_state_dict strict parameter.
        """
        self.handlers: list[SerializationHandler] = []
        self._depth = 0
        self._max_depth = 100
        self.strict = strict

    def register_handler(self, handler: SerializationHandler):
        """Register a serialization handler."""
        self.handlers.append(handler)

    def deserialize(self, data: Any, expected_type: type | None = None) -> Any:
        """Deserialize data using registered handlers."""
        self._depth += 1
        try:
            if self._depth > self._max_depth:
                raise DeserializationError(
                    f"Maximum recursion depth ({self._max_depth}) exceeded"
                )

            # Primitives pass through
            if data is None or isinstance(data, int | float | str | bool):
                return data

            # Try all handlers (including collection handlers)
            for handler in self.handlers:
                result = handler.deserialize(data, self)
                if result is not None:
                    return result

            return data
        finally:
            self._depth -= 1

__init__ #

__init__(strict: bool = True)

Initialize deserialization context.

Parameters:

Name Type Description Default
strict bool

If True (default), raise an error when serialized configs contain kwargs that no longer exist in the class signature. If False, emit a warning and ignore the extra kwargs. Similar to PyTorch's load_state_dict strict parameter.

True
Source code in src/confingy/serde.py
194
195
196
197
198
199
200
201
202
203
204
205
206
def __init__(self, strict: bool = True):
    """Initialize deserialization context.

    Args:
        strict: If True (default), raise an error when serialized configs contain
            kwargs that no longer exist in the class signature. If False, emit
            a warning and ignore the extra kwargs. Similar to PyTorch's
            load_state_dict strict parameter.
    """
    self.handlers: list[SerializationHandler] = []
    self._depth = 0
    self._max_depth = 100
    self.strict = strict

register_handler #

register_handler(handler: SerializationHandler)

Register a serialization handler.

Source code in src/confingy/serde.py
208
209
210
def register_handler(self, handler: SerializationHandler):
    """Register a serialization handler."""
    self.handlers.append(handler)

deserialize #

deserialize(
    data: Any, expected_type: type | None = None
) -> Any

Deserialize data using registered handlers.

Source code in src/confingy/serde.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def deserialize(self, data: Any, expected_type: type | None = None) -> Any:
    """Deserialize data using registered handlers."""
    self._depth += 1
    try:
        if self._depth > self._max_depth:
            raise DeserializationError(
                f"Maximum recursion depth ({self._max_depth}) exceeded"
            )

        # Primitives pass through
        if data is None or isinstance(data, int | float | str | bool):
            return data

        # Try all handlers (including collection handlers)
        for handler in self.handlers:
            result = handler.deserialize(data, self)
            if result is not None:
                return result

        return data
    finally:
        self._depth -= 1

PrimitiveHandler #

Bases: SerializationHandler

Handler for primitive types.

Source code in src/confingy/serde.py
239
240
241
242
243
244
245
246
247
248
249
250
251
class PrimitiveHandler(SerializationHandler):
    """Handler for primitive types."""

    def can_handle(self, obj: Any) -> bool:
        return obj is None or isinstance(obj, int | float | str | bool)

    def serialize(self, obj: Any, context: SerializationContext) -> Any:
        return obj

    def deserialize(self, data: Any, context: DeserializationContext) -> Any:
        if self.can_handle(data):
            return data
        return None

EnumHandler #

Bases: SerializationHandler

Handler for enum types.

Source code in src/confingy/serde.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
class EnumHandler(SerializationHandler):
    """Handler for enum types."""

    def can_handle(self, obj: Any) -> bool:
        return isinstance(obj, enum.Enum)

    def serialize(self, obj: Any, context: SerializationContext) -> dict[str, Any]:
        cls = type(obj)
        return {
            SerializationKeys.CLASS: cls.__name__,
            SerializationKeys.MODULE: get_module_name(cls),
            SerializationKeys.ENUM: True,
            SerializationKeys.NAME: obj.name,
        }

    def deserialize(self, data: Any, context: DeserializationContext) -> Any:
        if not isinstance(data, dict):
            return None

        if not data.get(SerializationKeys.ENUM):
            return None

        if SerializationKeys.CLASS not in data or SerializationKeys.MODULE not in data:
            return None

        try:
            module = importlib.import_module(data[SerializationKeys.MODULE])
            cls = getattr(module, data[SerializationKeys.CLASS])
            return cls[data[SerializationKeys.NAME]]
        except (ImportError, AttributeError, KeyError) as e:
            raise DeserializationError(
                f"Could not recreate enum {data[SerializationKeys.MODULE]}.{data[SerializationKeys.CLASS]}.{data.get(SerializationKeys.NAME)}: {e}"
            ) from None

PathHandler #

Bases: SerializationHandler

Handler for pathlib.Path objects.

Source code in src/confingy/serde.py
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
class PathHandler(SerializationHandler):
    """Handler for pathlib.Path objects."""

    _PATH_CLASSES = (
        "Path",
        "PosixPath",
        "WindowsPath",
        "PurePath",
        "PurePosixPath",
        "PureWindowsPath",
    )

    def can_handle(self, obj: Any) -> bool:
        return isinstance(obj, Path)

    def serialize(self, obj: Any, context: SerializationContext) -> dict[str, Any]:
        return {
            SerializationKeys.CLASS: "Path",
            SerializationKeys.MODULE: "pathlib",
            SerializationKeys.NAME: str(obj),
        }

    def deserialize(self, data: Any, context: DeserializationContext) -> Any:
        if not isinstance(data, dict):
            return None
        if data.get(SerializationKeys.CLASS) not in self._PATH_CLASSES:
            return None
        if data.get(SerializationKeys.MODULE) != "pathlib":
            return None
        return Path(data.get(SerializationKeys.NAME, ""))

DatetimeHandler #

Bases: SerializationHandler

Handler for datetime stdlib leaf types.

Covers datetime.date, datetime.datetime, datetime.time, and datetime.timedelta. Serialized as a leaf using the same {_confingy_class, _confingy_module, _confingy_name} envelope as :class:PathHandler.

Wire formats::

date       -> {"_confingy_class": "date",      "_confingy_module": "datetime", "_confingy_name": "2024-01-01"}
datetime   -> {"_confingy_class": "datetime",  "_confingy_module": "datetime", "_confingy_name": "2024-01-01T12:34:56+00:00"}
time       -> {"_confingy_class": "time",      "_confingy_module": "datetime", "_confingy_name": "12:34:56"}
timedelta  -> {"_confingy_class": "timedelta", "_confingy_module": "datetime", "_confingy_name": 93784.0}

date / datetime / time use isoformat() / fromisoformat(). Exact round-trip is guaranteed for values that isoformat() itself emits on the same Python version (the only values we ever feed back in).

timedelta uses total_seconds() (float) for the wire value because the stdlib has no timedelta.fromisoformat. total_seconds() preserves microsecond resolution exactly for every timedelta representable by the stdlib; sub-microsecond inputs are already clamped at construction time.

Dispatch is by exact type(obj) rather than isinstance because datetime.datetime subclasses datetime.date — a naive isinstance check would mis-serialize datetimes as dates.

Source code in src/confingy/serde.py
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
class DatetimeHandler(SerializationHandler):
    """Handler for ``datetime`` stdlib leaf types.

    Covers ``datetime.date``, ``datetime.datetime``, ``datetime.time``, and
    ``datetime.timedelta``. Serialized as a leaf using the same
    ``{_confingy_class, _confingy_module, _confingy_name}`` envelope as
    :class:`PathHandler`.

    Wire formats::

        date       -> {"_confingy_class": "date",      "_confingy_module": "datetime", "_confingy_name": "2024-01-01"}
        datetime   -> {"_confingy_class": "datetime",  "_confingy_module": "datetime", "_confingy_name": "2024-01-01T12:34:56+00:00"}
        time       -> {"_confingy_class": "time",      "_confingy_module": "datetime", "_confingy_name": "12:34:56"}
        timedelta  -> {"_confingy_class": "timedelta", "_confingy_module": "datetime", "_confingy_name": 93784.0}

    ``date`` / ``datetime`` / ``time`` use ``isoformat()`` / ``fromisoformat()``.
    Exact round-trip is guaranteed for values that ``isoformat()`` itself emits
    on the same Python version (the only values we ever feed back in).

    ``timedelta`` uses ``total_seconds()`` (float) for the wire value because the
    stdlib has no ``timedelta.fromisoformat``. ``total_seconds()`` preserves
    microsecond resolution exactly for every ``timedelta`` representable by the
    stdlib; sub-microsecond inputs are already clamped at construction time.

    Dispatch is by exact ``type(obj)`` rather than ``isinstance`` because
    ``datetime.datetime`` subclasses ``datetime.date`` — a naive isinstance
    check would mis-serialize datetimes as dates.
    """

    # Map of exact stdlib type -> (wire class name) used for both directions.
    _TYPES = {
        datetime.datetime: "datetime",
        datetime.date: "date",
        datetime.time: "time",
        datetime.timedelta: "timedelta",
    }

    def can_handle(self, obj: Any) -> bool:
        return type(obj) in self._TYPES

    def serialize(self, obj: Any, context: SerializationContext) -> dict[str, Any]:
        cls = type(obj)
        if cls is datetime.timedelta:
            name: Any = obj.total_seconds()
        else:
            name = obj.isoformat()
        return {
            SerializationKeys.CLASS: self._TYPES[cls],
            SerializationKeys.MODULE: "datetime",
            SerializationKeys.NAME: name,
        }

    def deserialize(self, data: Any, context: DeserializationContext) -> Any:
        if not isinstance(data, dict):
            return None
        if data.get(SerializationKeys.MODULE) != "datetime":
            return None
        class_name = data.get(SerializationKeys.CLASS)
        name = data.get(SerializationKeys.NAME)
        if class_name in ("date", "datetime", "time"):
            if not isinstance(name, str):
                return None
            if class_name == "date":
                return datetime.date.fromisoformat(name)
            if class_name == "datetime":
                return datetime.datetime.fromisoformat(name)
            return datetime.time.fromisoformat(name)
        if class_name == "timedelta":
            if not isinstance(name, (int, float)):
                return None
            return datetime.timedelta(seconds=float(name))
        return None

LazyHandler #

Bases: SerializationHandler

Handler for Lazy objects.

Source code in src/confingy/serde.py
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
class LazyHandler(SerializationHandler):
    """Handler for Lazy objects."""

    def can_handle(self, obj: Any) -> bool:
        return hasattr(obj, "_confingy_lazy_info")

    def serialize(self, obj: Any, context: SerializationContext) -> dict[str, Any]:
        result = {
            SerializationKeys.CLASS: obj._confingy_lazy_info["class"],
            SerializationKeys.MODULE: obj._confingy_lazy_info["module"],
            SerializationKeys.LAZY: True,
            SerializationKeys.CONFIG: {
                k: context.serialize(v, k) for k, v in obj._confingy_config.items()
            },
        }
        # Include class_hash if available
        if "class_hash" in obj._confingy_lazy_info:
            result[SerializationKeys.CLASS_HASH] = obj._confingy_lazy_info["class_hash"]
        return result

    def deserialize(self, data: dict[str, Any], context: DeserializationContext) -> Any:
        # Only handle dictionaries
        if not isinstance(data, dict):
            return None

        if not (
            data.get(SerializationKeys.LAZY)
            and SerializationKeys.CLASS in data
            and SerializationKeys.MODULE in data
        ):
            return None

        try:
            module = importlib.import_module(data[SerializationKeys.MODULE])
            cls = getattr(module, data[SerializationKeys.CLASS])
            actual_cls = getattr(cls, "_original_cls", cls)

            config = {
                k: context.deserialize(v)
                for k, v in data.get(SerializationKeys.CONFIG, {}).items()
            }

            # Filter out extra kwargs that no longer exist in the class signature
            config = _filter_extra_kwargs(
                actual_cls,
                config,
                context.strict,
                f"{data[SerializationKeys.MODULE]}.{data[SerializationKeys.CLASS]}",
            )

            return Lazy(
                actual_cls, config, skip_validation=True, _skip_post_config_hook=True
            )
        except (ImportError, AttributeError) as e:
            raise DeserializationError(
                f"Could not recreate {data[SerializationKeys.MODULE]}.{data[SerializationKeys.CLASS]}: {e}"
            ) from None

TrackedInstanceHandler #

Bases: SerializationHandler

Handler for tracked objects.

Source code in src/confingy/serde.py
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
class TrackedInstanceHandler(SerializationHandler):
    """Handler for tracked objects."""

    def can_handle(self, obj: Any) -> bool:
        return hasattr(obj, "_tracked_info")

    def serialize(self, obj: Any, context: SerializationContext) -> dict[str, Any]:
        info = obj._tracked_info
        result = {
            SerializationKeys.CLASS: info["class"],
            SerializationKeys.MODULE: info["module"],
            SerializationKeys.INIT: {
                k: context.serialize(v, k) for k, v in info["init_args"].items()
            },
        }
        # Include class_hash if available
        if "class_hash" in info:
            result[SerializationKeys.CLASS_HASH] = info["class_hash"]
        return result

    def deserialize(self, data: dict[str, Any], context: DeserializationContext) -> Any:
        # Only handle dictionaries
        if not isinstance(data, dict):
            return None

        if (
            SerializationKeys.INIT not in data
            or SerializationKeys.CLASS not in data
            or SerializationKeys.MODULE not in data
        ):
            return None

        try:
            module = importlib.import_module(data[SerializationKeys.MODULE])
            cls = getattr(module, data[SerializationKeys.CLASS])
            actual_cls = getattr(cls, "_original_cls", cls)

            init_args = {
                k: context.deserialize(v)
                for k, v in data[SerializationKeys.INIT].items()
            }

            # Filter out extra kwargs that no longer exist in the class signature
            init_args = _filter_extra_kwargs(
                actual_cls,
                init_args,
                context.strict,
                f"{data[SerializationKeys.MODULE]}.{data[SerializationKeys.CLASS]}",
            )

            # Use _create_tracked_instance to add tracking info to the instance
            # without globally modifying the class. This allows re-serialization
            # even if the class wasn't decorated with @track.
            return _create_tracked_instance(actual_cls, (), init_args, _validate=False)
        except (ImportError, AttributeError) as e:
            raise DeserializationError(
                f"Could not recreate {data[SerializationKeys.MODULE]}.{data[SerializationKeys.CLASS]}: {e}"
            ) from None

TypeHandler #

Bases: SerializationHandler

Handler for type objects.

Source code in src/confingy/serde.py
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
class TypeHandler(SerializationHandler):
    """Handler for type objects."""

    def can_handle(self, obj: Any) -> bool:
        return isinstance(obj, type)

    def serialize(self, obj: Any, context: SerializationContext) -> dict[str, Any]:
        # Check if the class can be imported
        if (
            hasattr(obj, "__module__")
            and hasattr(obj, "__qualname__")
            and (
                # Ensure it's not a local or lambda class
                "<locals>" not in obj.__qualname__
                and "<lambda>" not in obj.__qualname__
            )
        ):
            return {
                SerializationKeys.CLASS: "type",
                SerializationKeys.MODULE: get_module_name(obj),
                SerializationKeys.NAME: obj.__qualname__,
            }

        # Raise error for unserializable types
        raise SerializationError(
            f"Cannot serialize type {obj!r}: local or lambda types are not serializable. "
            f"Define the class at module level to make it serializable."
        )

    def deserialize(self, data: dict[str, Any], context: DeserializationContext) -> Any:
        # Only handle dictionaries
        if not isinstance(data, dict):
            return None

        # Check if this is a type serialization
        if data.get(SerializationKeys.CLASS) != "type":
            return None

        # Import and return the type
        if SerializationKeys.MODULE in data and SerializationKeys.NAME in data:
            try:
                module = importlib.import_module(data[SerializationKeys.MODULE])
                parts = data[SerializationKeys.NAME].split(".")
                obj = module
                for part in parts:
                    obj = getattr(obj, part)
                return obj
            except (ImportError, AttributeError) as e:
                raise DeserializationError(
                    f"Could not import type {data[SerializationKeys.MODULE]}.{data[SerializationKeys.NAME]}: {e}"
                ) from None

        return None

CallableHandler #

Bases: SerializationHandler

Handler for callable objects.

Source code in src/confingy/serde.py
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
class CallableHandler(SerializationHandler):
    """Handler for callable objects."""

    def can_handle(self, obj: Any) -> bool:
        return callable(obj) and not isinstance(obj, type)

    def serialize(self, obj: Any, context: SerializationContext) -> dict[str, Any]:
        # Handle bound methods
        if hasattr(obj, "__self__") and hasattr(obj.__self__, "_tracked_info"):
            return {
                SerializationKeys.CALLABLE: "method",
                SerializationKeys.OBJECT: context.serialize(
                    obj.__self__, "bound_object"
                ),
                SerializationKeys.METHOD: obj.__name__,
            }

        # Handle standalone functions
        if (
            hasattr(obj, "__module__")
            and hasattr(obj, "__qualname__")
            and (
                "<locals>" not in obj.__qualname__
                and "<lambda>" not in obj.__qualname__
            )
        ):
            return {
                SerializationKeys.CALLABLE: "function",
                SerializationKeys.MODULE: get_module_name(obj),
                SerializationKeys.NAME: obj.__qualname__,
            }

        raise SerializationError(
            f"Cannot serialize callable {obj!r}: lambdas and local functions are not serializable. "
            f"Define the function at module level to make it serializable."
        )

    def deserialize(self, data: dict[str, Any], context: DeserializationContext) -> Any:
        # Only handle dictionaries
        if not isinstance(data, dict):
            return None

        if SerializationKeys.CALLABLE not in data:
            return None

        # Handle serializable callables
        if data[SerializationKeys.CALLABLE] == "function":
            try:
                module = importlib.import_module(data[SerializationKeys.MODULE])
                parts = data[SerializationKeys.NAME].split(".")
                obj = module
                for part in parts:
                    obj = getattr(obj, part)
                return obj
            except (ImportError, AttributeError) as e:
                raise DeserializationError(
                    f"Could not import function {data[SerializationKeys.MODULE]}.{data[SerializationKeys.NAME]}: {e}"
                ) from None

        elif data[SerializationKeys.CALLABLE] == "method":
            obj = context.deserialize(data[SerializationKeys.OBJECT])
            return getattr(obj, data[SerializationKeys.METHOD]) if obj else None

        else:
            raise DeserializationError(
                f"Unknown callable type: {data[SerializationKeys.CALLABLE]}"
            )

CollectionHandler #

Bases: SerializationHandler

Handler for collections (lists, tuples, sets, dicts).

Source code in src/confingy/serde.py
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
class CollectionHandler(SerializationHandler):
    """Handler for collections (lists, tuples, sets, dicts)."""

    def can_handle(self, obj: Any) -> bool:
        return isinstance(obj, list | tuple | set | dict)

    def serialize(self, obj: Any, context: SerializationContext) -> Any:
        if isinstance(obj, tuple):
            return {
                SerializationKeys.TUPLE: True,
                SerializationKeys.ITEMS: [
                    context.serialize(item, f"[{i}]") for i, item in enumerate(obj)
                ],
            }
        elif isinstance(obj, set):
            return {
                SerializationKeys.SET: True,
                SerializationKeys.ITEMS: [
                    context.serialize(item, f"[{i}]") for i, item in enumerate(obj)
                ],
            }
        elif isinstance(obj, list):
            return [context.serialize(item, f"[{i}]") for i, item in enumerate(obj)]
        elif isinstance(obj, dict):
            return {str(k): context.serialize(v, str(k)) for k, v in obj.items()}

    def deserialize(self, data: Any, context: DeserializationContext) -> Any:
        if isinstance(data, list):
            return [context.deserialize(item) for item in data]
        elif isinstance(data, dict):
            # Handle tuple wrapper
            if data.get(SerializationKeys.TUPLE) is True:
                return tuple(
                    context.deserialize(item)
                    for item in data.get(SerializationKeys.ITEMS, [])
                )
            # Handle set wrapper
            elif data.get(SerializationKeys.SET) is True:
                return {
                    context.deserialize(item)
                    for item in data.get(SerializationKeys.ITEMS, [])
                }
            # Only handle regular dicts, not confingy special objects
            elif not any(k.startswith("_confingy_") for k in data):
                return {k: context.deserialize(v) for k, v in data.items()}
        return None

    def map_children(self, obj: Any, fn: Callable[[Any], Any]) -> Any:
        if isinstance(obj, list):
            return [fn(v) for v in obj]
        # Check for namedtuple before tuple (namedtuple is a subclass of tuple)
        if isinstance(obj, tuple) and hasattr(type(obj), "_fields"):
            return type(obj)(*[fn(v) for v in obj])
        if isinstance(obj, tuple):
            return tuple(fn(v) for v in obj)
        if isinstance(obj, set):
            return {fn(v) for v in obj}
        if isinstance(obj, dict):
            return {k: fn(v) for k, v in obj.items()}
        return obj

DataclassHandler #

Bases: SerializationHandler

Handler for dataclass objects.

Source code in src/confingy/serde.py
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
class DataclassHandler(SerializationHandler):
    """Handler for dataclass objects."""

    def can_handle(self, obj: Any) -> bool:
        return dataclasses.is_dataclass(obj) and not isinstance(obj, type)

    def serialize(self, obj: Any, context: SerializationContext) -> dict[str, Any]:
        cls = obj.__class__
        return {
            SerializationKeys.CLASS: cls.__name__,
            SerializationKeys.MODULE: get_module_name(cls),
            SerializationKeys.DATACLASS: True,
            SerializationKeys.FIELDS: {
                field.name: context.serialize(getattr(obj, field.name), field.name)
                for field in dataclasses.fields(obj)
            },
        }

    def deserialize(self, data: dict[str, Any], context: DeserializationContext) -> Any:
        # Only handle dictionaries
        if not isinstance(data, dict):
            return None

        if not (
            data.get(SerializationKeys.DATACLASS)
            and SerializationKeys.FIELDS in data
            and SerializationKeys.CLASS in data
            and SerializationKeys.MODULE in data
        ):
            return None

        try:
            module = importlib.import_module(data[SerializationKeys.MODULE])
            cls = getattr(module, data[SerializationKeys.CLASS])

            # Deserialize field values
            field_values = {
                k: context.deserialize(v)
                for k, v in data[SerializationKeys.FIELDS].items()
            }

            # Create the dataclass instance
            return cls(**field_values)
        except (ImportError, AttributeError, TypeError) as e:
            raise DeserializationError(
                f"Could not recreate dataclass {data[SerializationKeys.MODULE]}.{data[SerializationKeys.CLASS]}: {e}"
            ) from None

    def map_children(self, obj: Any, fn: Callable[[Any], Any]) -> Any:
        if not (dataclasses.is_dataclass(obj) and not isinstance(obj, type)):
            return obj
        changes = {}
        for field in dataclasses.fields(obj):
            # Skip init=False fields - dataclasses.replace() can't handle them
            if not field.init:
                continue
            old_value = getattr(obj, field.name)
            new_value = fn(old_value)
            if new_value is not old_value:
                changes[field.name] = new_value
        if changes:
            return dataclasses.replace(obj, **changes)
        return obj

HandlerRegistry #

Central registry for serialization and deserialization handlers.

Source code in src/confingy/serde.py
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
class HandlerRegistry:
    """Central registry for serialization and deserialization handlers."""

    @staticmethod
    def get_default_handlers():
        """Get the default set of handlers in the correct order."""
        return [
            PathHandler(),  # Must be before PrimitiveHandler (Path is not a primitive)
            EnumHandler(),  # Must be before PrimitiveHandler (StrEnum/IntEnum are str/int)
            DatetimeHandler(),  # Must be before PrimitiveHandler (datetime types are leaves, not primitives)
            PrimitiveHandler(),
            LazyHandler(),
            TrackedInstanceHandler(),
            DataclassHandler(),
            TypeHandler(),  # Handle type objects before callables
            CallableHandler(),
            CollectionHandler(),
        ]

get_default_handlers staticmethod #

get_default_handlers()

Get the default set of handlers in the correct order.

Source code in src/confingy/serde.py
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
@staticmethod
def get_default_handlers():
    """Get the default set of handlers in the correct order."""
    return [
        PathHandler(),  # Must be before PrimitiveHandler (Path is not a primitive)
        EnumHandler(),  # Must be before PrimitiveHandler (StrEnum/IntEnum are str/int)
        DatetimeHandler(),  # Must be before PrimitiveHandler (datetime types are leaves, not primitives)
        PrimitiveHandler(),
        LazyHandler(),
        TrackedInstanceHandler(),
        DataclassHandler(),
        TypeHandler(),  # Handle type objects before callables
        CallableHandler(),
        CollectionHandler(),
    ]