typedload

2.40 · active · verified Sat Mar 28

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

Install

Imports

Quickstart

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.

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'

view raw JSON →