typedload
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.
Warnings
- gotcha Untagged Unions can lead to non-deterministic loading results if input data matches multiple types within the union. While `typedload` supports untagged unions, it's safer and faster to use `Literal` fields to tag unions for explicit type identification. For debugging, `uniondebugconflict=True` can detect such ambiguities but incurs a performance cost.
- gotcha The distinction between `typing.Optional[T]` and a field with a default value is important. `Optional[T]` means the field *must* be present in the input data but can be `None`. A field with a default value, however, can be entirely *omitted* from the input data, and `typedload` will use the default. Misunderstanding this can lead to unexpected validation errors.
- breaking Directly using a bare `list` (e.g., `my_list: list`) as a type annotation for loading into a dataclass field will cause a crash. This annotation is treated differently by `typedload` and is not equivalent to `list[typing.Any]` at runtime.
- deprecated Since version 2.23, the default behavior for dumping `datetime.date`, `datetime.time`, and `datetime.datetime` objects has shifted. The previous method of dumping them as a list of integers (e.g., `[year, month, day, ...]`) is now deprecated. The recommended way is to dump them as ISO 8601 strings.
Install
-
pip install typedload
Imports
- load
from typedload import load
- dump
from typedload import dump
Quickstart
import dataclasses
from typing import NamedTuple, List
from typedload import load, dump
@dataclasses.dataclass
class User:
username: str
shell: str = 'bash'
sessions: List[str] = dataclasses.field(default_factory=list)
class Logins(NamedTuple):
users: List[User]
data_from_json = {
'users': [
{ 'username': 'salvo', 'shell': 'bash', 'sessions': ['pts/4', 'tty7', 'pts/6'] },
{ 'username': 'lop' }
]
}
# Load the dictionary into typed data structures
loaded_data: Logins = load(data_from_json, Logins)
print(f"Loaded Data: {loaded_data}")
assert loaded_data.users[0].username == 'salvo'
assert loaded_data.users[1].shell == 'bash' # Default value applied
# Dump the typed data structure back to a dictionary
dumped_data = dump(loaded_data)
print(f"Dumped Data: {dumped_data}")
assert dumped_data['users'][0]['username'] == 'salvo'