Quantcast
Channel: User Sourav Kannantha B - Stack Overflow
Viewing all articles
Browse latest Browse all 60

Answer by Sourav Kannantha B for Python dataclass from a nested dict

$
0
0

I came across this apischema library. It provides both serialization and deserialization of data-dataclasses.

Here is an example:

from apischema import deserialize, serialize# Define a schema with standard dataclasses@dataclassclass Resource:    id: UUID    name: str    tags: set[str] = field(default_factory=set)# Get some datauuid = uuid4()data = {"id": str(uuid), "name": "wyfo", "tags": ["some_tag"]}# Deserialize dataresource = deserialize(Resource, data)assert resource == Resource(uuid, "wyfo", {"some_tag"})# Serialize objectsassert serialize(Resource, resource) == data

This even works with Python 3.12 generic (data)classes. This uses dataclass type hinting to validate input and then generate object from it.


Viewing all articles
Browse latest Browse all 60

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>