typedload is a Python library designed to load and dump data from JSON-like formats into statically typed data structures. It supports standard Python types such as NamedTuples, dataclasses, sets, and enums, enforcing a schema by performing type checks and casts as needed. It also facilitates dumping typed data structures back to JSON-like dictionaries and lists. This library is particularly useful for projects leveraging Mypy, as it guarantees data conformity to specified schemas at runtime. It is actively maintained, with frequent releases; the current version is 2.40.
pip install typedloadVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to define typed data structures using dataclasses and NamedTuple, then use `typedload.load` to convert a dictionary (typically from JSON) into these structures. It also shows `typedload.dump` for converting them back to a dictionary. Default values for fields are automatically handled during loading.
Prefer using tagged unions with `typing.Literal` to explicitly differentiate types. If untagged unions are necessary, ensure data unambiguously maps to a single type or be aware of potential non-deterministic behavior. Use `load(data, SomeUnion, uniondebugconflict=True)` for debugging.
Always provide `None` explicitly for `Optional[T]` fields in input data if the value is `None`. For truly optional fields that can be omitted, define a default value (e.g., `field: str = 'default'` or `field: List[str] = dataclasses.field(default_factory=list)`).
Always specify the type argument for generic collections like `list`. Use `my_list: list[Any]` or `my_list: list[str]` (or any specific type) instead of `my_list: list`.
When dumping `datetime` objects and desiring ISO 8601 strings, ensure `isodates=True` is passed to the `dump` function (e.g., `typedload.dump(obj, isodates=True)`). If relying on the old integer list format, be aware it may be removed in future major versions.
If all fields must always be present in the dumped output, regardless of whether their value matches a default, ensure that `typedload.dump` is configured to include all fields (e.g., check for an `omit_defaults=False` or similar option). Alternatively, if possible, avoid assigning default values to fields that must always be present in the serialized output.
pip install typedload
Ensure the input data's type or value is compatible with the expected type for the field or target class.
Ensure the input dictionary contains all required keys for the target type.
from typedload.exceptions import TypedloadException