Skip to main content

Create data structures from dictionaries.

Project description

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.List and typing.Dict type 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}")

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

from_dict-0.4.3.tar.gz (17.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

from_dict-0.4.3-py3-none-any.whl (8.8 kB view details)

Uploaded Python 3

File details

Details for the file from_dict-0.4.3.tar.gz.

File metadata

  • Download URL: from_dict-0.4.3.tar.gz
  • Upload date:
  • Size: 17.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for from_dict-0.4.3.tar.gz
Algorithm Hash digest
SHA256 cfd06f8403bde4dc6104eaf1bef28c644c492db84364eed33d6c51c9bdaec84b
MD5 79d68f0b716995c0d975d0636d24c831
BLAKE2b-256 d661c3d1eeed428c86c64f5d5d7232c430997b3eddfa64f72fb71e57eec3443a

See more details on using hashes here.

File details

Details for the file from_dict-0.4.3-py3-none-any.whl.

File metadata

  • Download URL: from_dict-0.4.3-py3-none-any.whl
  • Upload date:
  • Size: 8.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for from_dict-0.4.3-py3-none-any.whl
Algorithm Hash digest
SHA256 9ce45cf9de512a0a0c0156fbc83c7c51936c50456d952f4efd5f5f3a73e8034d
MD5 750d7624bf3cf39660fe8905c52fd0cb
BLAKE2b-256 c76e56bcab63d6cee293be57283adbdc0729e3cf9829b2851d3658c2647c6f11

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page