Skip to main content

Easily serialize dataclasses to and from JSON

Project description

serious

PyPI Build Status Test Coverage Supported Python Documentation

A dataclass model toolkit: serialization, validation, and more.

Documentation

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')

More on validation.

Supported formats:

Supported field types

More in docs.

  • 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, ...])
  • Enumerations by value:
    • of primitives (e.g. OperatingSystem(Enum))
    • typed enums (Color(str, Enum) and FilePermission(IntFlag))
  • 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 value
  • serious.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


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.4.tar.gz (27.7 kB view details)

Uploaded Source

Built Distribution

serious-1.5.4-py3-none-any.whl (33.3 kB view details)

Uploaded Python 3

File details

Details for the file serious-1.5.4.tar.gz.

File metadata

  • Download URL: serious-1.5.4.tar.gz
  • Upload date:
  • Size: 27.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.10.15

File hashes

Hashes for serious-1.5.4.tar.gz
Algorithm Hash digest
SHA256 0a298e4a6d15fce4deb1a9a9cab73dedb7294d0895c195cb45011e2ba020fa09
MD5 14a2b32f330cdbe8cbead564a4dfeea0
BLAKE2b-256 7e2974e7f230db21f18891aa263656b6ef7abf68a35c4a31c33c6100bc433a96

See more details on using hashes here.

File details

Details for the file serious-1.5.4-py3-none-any.whl.

File metadata

  • Download URL: serious-1.5.4-py3-none-any.whl
  • Upload date:
  • Size: 33.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.10.15

File hashes

Hashes for serious-1.5.4-py3-none-any.whl
Algorithm Hash digest
SHA256 6eafbe7234ea2f5dfdd896fef1678fef6e5cb5b7497ef6d50f8e4b757c60a6ff
MD5 360427c5794dc92bfa09d392bc4afd62
BLAKE2b-256 56b55c2666a23d7e3b835ccffe6f6fbba220e86e1e9297cc7f04ebbe5f47948d

See more details on using hashes here.

Supported by

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