Convert heirarchies of dicts/list/sets/values (JSON?) to heirarchies of type annotated dataclasses.
Project description
dictaclass - dicts to dataclasses
Have you ever been handed an "example JSON" and wanted to have it in an intellisense-friendly structure?
Just define the JSON structure as a hierarchy of dataclasses and run to_dataclass(MyJsonDataclass, json.loads(source))
Well, the library works with whatever source of data you have, as long as you can represent the way json.loads
does - dict
s, list
s, and values.
Features
- Supports deeply nested dataclasses (duh)
- Supports inheritance
- Supports collections
list
set
dict
- Supports
frozen
dataclasses - Supports timestamps as
datetime
objects
Limitations
- Requires Python 3.7+
- Cannot guess types.
- Cannot use mixed types.
- Cannot use Union[].
- Cannot use Tuple[].
Installation
py -m pip install dictaclass
or
python3 -m pip install dictaclass
Example
from typing import Set
from dataclasses import dataclass
from dictaclass import to_dataclass
import json
@dataclass(frozen=True)
class Pair:
first: str
last: str
@dataclass(frozen=True)
class PairPair:
a: Pair
@dataclass(frozen=True)
class Object:
pairs: Set[PairPair]
v = to_dataclass(
Object,
{
"pairs": [
{"a": {"first": "f0", "last": "l0"}},
{"a": {"first": "f1", "last": "l1"}},
]
},
)
# or
v = to_dataclass(
Object,
json.loads(
"""
{
"pairs": [
{"a": {"first": "f0", "last": "l0"}},
{"a": {"first": "f1", "last": "l1"}}
]
}
"""
),
)
assert isinstance(v, Object)
assert isinstance(v.pairs, set) # it was a list in the JSON
assert len(v.pairs) == 2
assert v.pairs == {
PairPair(Pair("f0", "l0")),
PairPair(Pair("f1", "l1"))
}
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
Built Distribution
File details
Details for the file dictaclass-0.6.0.tar.gz
.
File metadata
- Download URL: dictaclass-0.6.0.tar.gz
- Upload date:
- Size: 10.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.0.0 CPython/3.12.1
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | f5da6ff17fc3c4c26fe0a9edf73d2d79f83a18cfb20ad33277f4e1b8c2fb892b |
|
MD5 | f97c523eb93a8f6cfe586f8933629a6a |
|
BLAKE2b-256 | d9501663ad54a143d1bb60e845a7d5262a363e435e38e6e69c2b66c1090dec04 |
File details
Details for the file dictaclass-0.6.0-py3-none-any.whl
.
File metadata
- Download URL: dictaclass-0.6.0-py3-none-any.whl
- Upload date:
- Size: 8.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.0.0 CPython/3.12.1
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 787ec77f5f99996a03295ce775145886db7520fbe7ca78e5168bc3565ac6b722 |
|
MD5 | d55c07648d0fcc9143d62ffcf5430c76 |
|
BLAKE2b-256 | 50133a57c8bb01fbf5b6a7e77032bbec14b76f5a791c5c430543650e2ae5eadb |