from-dict
Create data structures from partially known dictionaries.
Features
- Transform dicts to
attr.s,dataclass,NamedTuple, and normal classes that have type-hints for all their init parameters. - Supports nested structures when using
typing.Listandtyping.Dicttype hints. - Insert additional fields existing in dict into structure with
fd_copy_unknown=True - Optional run-time type-checking with
fd_check_types=True - Supports forward references
- Raise an exception if there are more arguments supplied than are required with
fd_error_on_unknown=True - Supports Literal type hints
Example
from dataclasses import dataclass
from typing import List, Optional
from from_dict import from_dict
@dataclass(frozen=True)
class Preference:
name: str
score: int
@dataclass(frozen=True)
class Customer:
name: str
nick_name: Optional[str]
preferences: List[Preference]
input_customer_data = {
"name": "Christopher Lee",
"nick_name": None,
"preferences": [
{ "name": "The Hobbit", "score": 37 },
{ "name": "Count Dooku", "score": 2 },
{ "name": "Saruman", "score": 99 }
],
"friend": "Mellon"
}
customer = from_dict(Customer, input_customer_data)
# Structured data is available as attributes since attr.s exposes them like that
assert customer.name == "Christopher Lee"
# Nested structures are also constructed. List[sub_strucutre] and Dict[key, sub_structure] are supported
assert customer.preferences[0].name == "The Hobbit"
# Data not defined in the strucutre is inserted into the __dict__ if possible
assert customer.__dict__["friend"] == "Mellon"
Use cases
from-dict is especially useful when used on big and partially known data structures like JSON. Since undefined
structure is ignored, we can use from-dict to avoid try-catch and KeyError hell:
Assume we want to interact with the Google GeoCoding API (cf. https://developers.google.com/maps/documentation/geocoding/intro):
The JSON that is returned on requests contains some keys that we are not interested in. So we create data-structures that contain the keys that we actually want to use:
from dataclasses import dataclass
from typing import List
@dataclass(frozen=True)
class AddressComponent:
long_name: str
short_name: str
types: List[str]
@dataclass(frozen=True)
class Result:
address_components: List[AddressComponent]
formatted_address: str
@dataclass(frozen=True)
class Response:
results: List[Result]
With that, given the response of the API, we can extract the fields and ignore everything else.
from from_dict import from_dict
# This will throw a TypeError if something goes wrong.
structured_response: Response = from_dict(Response,
response,
fd_check_types=True, # Do check types at run-time
fd_copy_unknown=False # Do not copy undefined data to __dict__
)
# Now, we can access the data in a statically known manner
for res in structured_response.results:
print(f"The formatted address is {res.formatted_address}")
for addr_comp in res.address_components:
print(f"Component {addr_comp.long_name}")
Metadata
Release files for from-dict 0.5.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| from_dict-0.5.0.tar.gz | 17.2 kB | Without provenance | Details for from_dict-0.5.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| from_dict-0.5.0-py3-none-any.whl | Python 3 | none | any | Details for from_dict-0.5.0-py3-none-any.whl |
Total release size: 26.0 kB
Release files / from_dict-0.5.0.tar.gz
| Download URL | from_dict-0.5.0.tar.gz |
|---|---|
| Size | 17.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
87436c029e7bb03a12c4d4b68f7eddecf2fced51724467e8c27db0ef78690251
|
|
BLAKE2b-256 checksum How to use checksums |
7778145df1f28578c5df6715799cfab3448338d8f51528ad3bbae2cb0c409c26
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.13.2
|
Release files / from_dict-0.5.0-py3-none-any.whl
| Download URL | from_dict-0.5.0-py3-none-any.whl |
|---|---|
| Size | 8.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
6b6656cfddd03726c60bf33f8220e2b6d64f072676a41569ad605ad05bb951a9
|
|
BLAKE2b-256 checksum How to use checksums |
9f9455cf653c6a3c572b0619a431763666c5a445560fd77e14a97232a4711283
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.13.2
|
Security for from-dict 0.5.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.