An utility class for creating instances of dataclasses
Project description
dataclass_factory
Why
You can convert dataclass to dict using asdict
method, but cannot convert back.
This module provides parse
method for such task.
What's supported
dataclass
from dictEnum
from valueList
,Set
,FrozenSet
,Dict
with specified typeTuple
with specified types or ellipsisOptional
with specified typeUnion
parsed in order of given typesAny
returned as is- other classes based on their
__init__
method int
/float
/decimal
also parsed from string
Usage
Install:
pip install dataclass_factory
Code:
@dataclass
class Book:
title: str
author: str = "Unknown author"
data = {
"title": "Fahrenheit 451"
}
obj = dataclass_factory.parse(data, Book) # Same as Book(title="Fahrenheit 451")
More complex example
@dataclass
class Disk:
title: str
artist: str
@dataclass
class Store:
items: List[Union[Disk, Book]]
data = {
"items": [
{"title": "Fahrenheit 451", "author": "Bradbury"},
{"title": "Dark Side of the Moon", "artist": "Pink Floyd"}
]
}
expected = Store(
items=[
Book(title='Fahrenheit 451', author='Bradbury'),
Disk(title='Dark Side of the Moon', artist='Pink Floyd')
]
)
assert expected == dataclass_factory.parse(data, Store)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
dataclass_factory-0.7.tar.gz
(4.4 kB
view hashes)