Registry / serialization / dacite

dacite

JSON →
library1.9.2pypypi✓ verified 26d ago

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.

pip install dacite
INSTALL
IMPORT
SIG · DACITE
D
dacite
serializationpythonv1.9.2
Install
1.6s avg
Import
42ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.9.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.044s · 17.9MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.6s · import 0.040s · 18MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

from_dict
from dacite import from_dict
The primary function for converting dictionaries to dataclasses.
Config
from dacite import from_dict, Config
Used to customize the conversion process, e.g., for type hooks or case conversion.

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)
Debug
Known issues
gotchaDacite is a data-to-object mapping library, not a data validation library. It primarily focuses on converting dictionaries to dataclass instances based on type hints. For robust data validation, it's recommended to combine Dacite with a dedicated validation library.
fix
Integrate with a data validation library (e.g., Pydantic, Marshmallow) before passing data to `dacite.from_dict` if validation is required.
affects: All versions
gotchaBy default, Dacite expects all non-optional fields in the target dataclass to have corresponding keys in the input dictionary. If a required field is missing from the input dictionary and does not have a default value in the dataclass, a `MissingValueError` will be raised.
fix
Ensure all required dictionary keys are present, or provide default values for optional fields in your dataclass definitions.
affects: All versions
gotchaDacite performs basic type checking but does not automatically coerce types by default (e.g., converting a string '123' to an integer 123 for an `int` field), which can lead to `WrongTypeError`. Automatic casting needs to be explicitly enabled.
fix
Use `Config(cast=[YourType])` to enable casting for specific types, or `Config(type_hooks={YourType: lambda v: YourType(v)})` for custom transformations. Note that `cast` works for base types and their subtypes.
affects: All versions
gotchaWhen using `typing.Union`, Dacite by default tries to find the first matching type. If `Config(strict_unions_match=True)` is used, it will raise a `StrictUnionMatchError` if more than one type in the Union could match the input data.
fix
Carefully define `Union` types to avoid ambiguity or handle `StrictUnionMatchError` if `strict_unions_match` is enabled. Consider the order of types in the Union if multiple types could potentially match the input data without `strict_unions_match`.
affects: All versions
gotchaDacite does not dynamically add fields to dataclasses that are not predefined in the dataclass definition. If your input dictionary contains keys not present in the dataclass, those keys will be ignored during conversion unless `Config(check_types=False)` is used (which is not recommended for type safety).
fix
Ensure your dataclass definition accurately reflects all fields you intend to deserialize. If you have genuinely dynamic keys, consider using `dict` types within your dataclass for those sections.
affects: All versions
Errors
Common errors & fixes
dacite.exceptions.WrongTypeError: wrong value type for field "<field_name>" - should be "<expected_type>" instead of value "<value>" of type "<actual_type>"
The type of the input value in the dictionary does not match the expected type hint defined in the dataclass field, and dacite's default behavior does not perform automatic casting.
fix
Ensure the input data types precisely match the dataclass type hints, or enable casting for specific types using `dacite.Config(cast=[<TypeToCast>])` or provide a `type_hook` for complex conversions. For example, to allow integers for a float field, use `Union[int, float]` or configure casting for floats.
dacite.exceptions.MissingValueError: missing value for field "<field_name>"
A required field in the dataclass (one without a default value or `Optional` annotation) is not present in the input dictionary provided to `from_dict`.
fix
Ensure all required fields are present in the input dictionary, or make the dataclass field optional using `typing.Optional[<Type>]` (e.g., `Optional[str]`) or by providing a default value (e.g., `field: str = 'default'`).
dacite.exceptions.UnionMatchError: can not match type "<actual_type>" to any type of "<field_name>" union: <Union[Type1, Type2]>
The input value for a field annotated with `typing.Union` does not successfully match any of the types specified within that union.
fix
Verify that the input data conforms to one of the types in the `Union`. For complex union types, ensure nested structures or values correctly align with one of the union's member types. Sometimes, adjusting the order of types in `Union` or providing specific `type_hooks` can help resolve ambiguities.
dacite.exceptions.UnexpectedDataError: unexpected keys in input data: <key1>, <key2>
The `dacite.Config` was set with `strict=True`, but the input dictionary contains keys that are not defined as fields in the target dataclass.
fix
Either remove the extraneous keys from the input dictionary, or set `strict=False` in the `dacite.Config` to allow dacite to ignore unexpected keys: `from_dict(MyDataClass, data, config=Config(strict=False))`.
Upgrade
Version history
1.9.2latest on PyPI · released Feb 5, 2025
Audit
Dependencies

No dependency data recorded yet.

Agent activity
27 hits · last 30 days
node
26
Resources
dacite — pip install dacite · libregistry