Easily serialize dataclasses to and from JSON
Project description
serious
A dataclass model toolkit: serialization, validation, and more.
Features
- Model definitions in pure Python.
- Validation showing up in code coverage.
- Type annotations for all public-facing APIs.
- (Optionally) ensures immutability.
- Easily extensible.
- Made for people.
- Documented rigorously.
Basics
Installation
Available from PyPI:
pip install serious
Quick Example
Central part of Serious API are different Models.
Given a regular dataclass:
from dataclasses import dataclass
@dataclass
class Person:
name: str
Let’s create a JsonModel
:
from serious.json import JsonModel
model = JsonModel(Person)
And use its dump/load methods:
person = Person('Albert Einstein')
model.dump(person) # {"name": "Albert Einstein"}
Validation
To add validation to the example above all we need is to add __validate__
method to person:
from dataclasses import dataclass
from typing import Optional
from serious import ValidationError, Email
@dataclass
class Person:
name: str
email: Optional[Email]
phone: Optional[str]
def __validate__(self):
if len(self.name) == 0:
raise ValidationError('Every person needs a name')
if self.phone is None and self.email is None:
raise ValidationError('At least some contact should be present')
Supported formats:
- JSON
- Python Dictionaries
- YAML
- Form data
Supported field types
- Other dataclasses
- Primitives:
str
,int
,float
,bool
- Dictionaries: only with string keys:
Dict[str, Any]
- Lists, sets, deques: python collections of any serializable type
- Tuples both with and without ellipsis:
- tuples as set of independent elements (e.g.
Tuple[str, int, date]
) - with ellipses, acting as a frozen list (
Tuple[str, ...]
)
- tuples as set of independent elements (e.g.
- Enumerations by value:
- of primitives (e.g.
OperatingSystem(Enum)
) - typed enums (
Color(str, Enum)
andFilePermission(IntFlag)
)
- of primitives (e.g.
- Decimal: encoded to JSON as string
- Datetime, date and time: encoded to the ISO 8601 formatted string
- UUID
serious.types.Timestamp
: a UTC timestamp since UNIX epoch as float ms valueserious.types.Email
: a string Tiny Type that supports validation and contains additional properties- custom immutable alternatives to native python types in
serious.types
:FrozenList
,FrozenDict
A bigger example
from dataclasses import dataclass
from serious import JsonModel, ValidationError
from typing import List
from enum import Enum
class Specialty(Enum):
Worker = 1
Fool = 2
@dataclass(frozen=True)
class Minion:
name: str
type: Specialty
@dataclass(frozen=True)
class Boss:
name: str
minions: List[Minion]
def __validate__(self):
if len(self.minions) < 2:
raise ValidationError('What kind of boss are you?')
boss = Boss("me", [Minion('evil minion', Specialty.Fool), Minion('very evil minion', Specialty.Worker)])
boss_json = """{
"name": "me",
"minions": [
{
"name": "evil minion",
"type": "Fool"
},
{
"name": "very evil minion",
"type": "Worker"
}
]
}"""
model = JsonModel(Boss, indent=4)
assert model.dump(boss) == boss_json
assert model.load(boss_json) == boss
Acknowledgements
Initially, a fork of @lidatong/dataclasses-json.
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
serious-1.5.2.tar.gz
(27.6 kB
view details)
Built Distribution
serious-1.5.2-py3-none-any.whl
(33.2 kB
view details)
File details
Details for the file serious-1.5.2.tar.gz
.
File metadata
- Download URL: serious-1.5.2.tar.gz
- Upload date:
- Size: 27.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.10.14
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 3697dee55d2813f51a20ceb0eb163c145e4db73add1d37658ca5e91c4701407e |
|
MD5 | 6b287b6b5c5c5d979e28bf7217d9c148 |
|
BLAKE2b-256 | 5b18c74408bce4d9efeecf1375574aaa5857e751cf6602abecc92ff1d34c9a73 |
File details
Details for the file serious-1.5.2-py3-none-any.whl
.
File metadata
- Download URL: serious-1.5.2-py3-none-any.whl
- Upload date:
- Size: 33.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.10.14
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | b53f983004571d5e9f57f34f602a9aca878aa377799c2b4616af13f1686dead4 |
|
MD5 | cab917046e7cfc3718bb3a16c2ca0603 |
|
BLAKE2b-256 | 540aa384397a83f8b8b359975a1950ce5f2f8beb85c3b17a0ba32fbaa71447cb |