Dacite

1.9.2 · active · verified Sun Mar 29

Dacite is a Python library that simplifies the creation of data class instances from dictionaries. It focuses on converting raw dictionary data (e.g., from HTTP requests or databases) into robust, type-hinted dataclass objects, leveraging PEP 557 dataclasses. The library is actively maintained, with version 1.9.2 released recently, and receives regular updates including performance improvements and new feature support like generics, forward references, and unions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to convert a dictionary into a nested dataclass structure using `from_dict`. It also shows how to use the `Config` object to apply custom type hooks for transformation during the conversion process.

from dataclasses import dataclass
from dacite import from_dict, Config

@dataclass
class User:
    name: str
    age: int
    is_active: bool

@dataclass
class Address:
    street: str
    city: str

@dataclass
class Profile:
    user: User
    address: Address
    preferences: dict

data = {
    'user': {'name': 'Jane Doe', 'age': 28, 'is_active': False},
    'address': {'street': '123 Main St', 'city': 'Anytown'},
    'preferences': {'theme': 'dark', 'notifications': True}
}

# Basic conversion
profile = from_dict(data_class=Profile, data=data)
print(profile)
# Expected: Profile(user=User(name='Jane Doe', age=28, is_active=False), address=Address(street='123 Main St', city='Anytown'), preferences={'theme': 'dark', 'notifications': True})

# Example with a type hook (e.g., converting all strings to uppercase)
@dataclass
class Item:
    id: str
    value: int

def uppercase_str(s: str) -> str:
    return s.upper()

item_data = {'id': 'item-abc', 'value': 100}
config_with_hook = Config(type_hooks={str: uppercase_str})
item = from_dict(data_class=Item, data=item_data, config=config_with_hook)
print(item)
# Expected: Item(id='ITEM-ABC', value=100)

view raw JSON →