Dataclass serialization¶
These helpers are independent of facts and collector modules. Use
json.dumps(value, default=json_default) and
json.loads(payload, object_hook=json_object_hook) to preserve dataclasses and
bytes alongside ordinary JSON values. The default hook uses singledispatch;
the object hook handles tagged records through pattern matching.
Bytes use {"_type": "bytes", "_value": "AP8="} (base64). Dataclasses use
{"_type": "dataclass", "_value": {"class": "module:qualname", "fields": {...}}}.
Fields are read shallowly; json handles nested values without an asdict or
deepcopy pass. Constructor fields are saved, and init=False fields are
recomputed by the restored model.
The exact two-key _type/_value shape is reserved, including in raw data.
Unknown or malformed tagged records raise an error. Other dictionary shapes
are unchanged. Decode only trusted data: restoring a dataclass imports its
class and calls its constructor. JSON’s usual rules apply to native containers,
including tuples becoming lists and supported non-string keys becoming strings.
Sets, arbitrary objects and immutable mapping wrappers are unsupported unless
the caller supplies an appropriate serializer.
Small JSON hooks for dataclasses and bytes, independent of tool schemas.
The exact two-key shape {"_type": ..., "_value": ...} is reserved for
encoded values. Decode only trusted data: dataclass records import their class
and call its constructor. Ordinary JSON containers are handled by json itself.
- class rmote.serialization.Dataclass(*args, **kwargs)[source]¶
Bases:
ProtocolStructural type for a dataclass instance, independent of collectors.
- rmote.serialization.dump_dataclass(value)[source]¶
Export an entire dataclass tree to JSON-compatible tagged dictionaries.
This convenience helper materializes a tree through JSON. Backends use json_default directly instead, avoiding this intermediate representation.
- rmote.serialization.json_default(value)[source]¶
- rmote.serialization.json_default(value)
JSON default hook for dataclasses, extensible through singledispatch.
Values already supported by json do not pass through this hook. For a dataclass it emits a class path and shallow constructor-field mapping; json recursively visits their values. No asdict or deepcopy is performed. Unknown objects raise TypeError. init=False fields are recomputed on load.