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 daciteVerified import paths — ran on the pinned version, not inferred.
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.
Integrate with a data validation library (e.g., Pydantic, Marshmallow) before passing data to `dacite.from_dict` if validation is required.
Ensure all required dictionary keys are present, or provide default values for optional fields in your dataclass definitions.
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.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`.
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.
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.
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'`).
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.
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))`.
No dependency data recorded yet.