Skip to main content

No project description provided

Project description

serpyco-rs: a serializer for python dataclasses

PyPI version Python versions CI status

What is serpyco-rs ?

Serpyco is a serialization library for Python 3.9+ dataclasses that works just by defining your dataclasses:

import dataclasses
import serpyco_rs

@dataclasses.dataclass
class Example:
    name: str
    num: int
    tags: list[str]


serializer = serpyco_rs.Serializer(Example)

result = serializer.dump(Example(name="foo", num=2, tags=["hello", "world"]))
print(result)

>> {'name': 'foo', 'num': 2, 'tags': ['hello', 'world']}

serpyco-rs works by analysing the dataclass fields and can recognize many types : list, tuple, Optional... You can also embed other dataclasses in a definition.

The main use-case for serpyco-rs is to serialize objects for an API, but it can be helpful whenever you need to transform objects to/from builtin Python types.

Installation

Use pip to install:

$ pip install serpyco-rs

Features

  • Serialization and deserialization of dataclasses
  • Validation of input/output data
  • Very fast
  • Support recursive schemas
  • Generate JSON Schema Specification (Draft 2020-12)
  • Support custom encoders/decoders for fields

Supported field types

There is support for generic types from the standard typing module:

  • Decimal
  • UUID
  • Time
  • Date
  • DateTime
  • Enum
  • List
  • Dict
  • Mapping
  • Sequence
  • Tuple (fixed size)
  • Literal[str, ...]
  • Tagged unions (restricted)

Benchmark

macOS Monterey / Apple M1 Pro / 16GB RAM / Python 3.11.0

dump

Library Median latency (milliseconds) Operations per second Relative (latency)
serpyco_rs 0.05 22188.2 1
serpyco 0.05 20878.5 1.06
mashumaro 0.06 15602.7 1.42
pydantic 2.66 375.6 59
marshmallow 1.05 951.7 23.33

load with validate

Library Median latency (milliseconds) Operations per second Relative (latency)
serpyco_rs 0.23 4400.1 1
serpyco 0.28 3546.4 1.24
mashumaro 0.23 4377.7 1.01
pydantic 2.01 497.3 8.86
marshmallow 4.55 219.9 20.03

load (only serpyco and serpyco_rs supported load without validate)

Library Median latency (milliseconds) Operations per second Relative (latency)
serpyco_rs 0.07 13882.9 1
serpyco 0.08 12424.5 1.12
mashumaro 0.23 4382.9 3.17
pydantic 2.02 494.4 28.09
marshmallow 4.59 217.5 63.8

Supported annotations

serpyco-rs supports changing load/dump behavior with typing.Annotated.

Currently available:

  • Alias
  • FiledFormat (CamelCase / NoFormat)
  • NoneFormat (OmitNone / KeepNone)
  • Discriminator
  • Min / Max
  • MinLength / MaxLength

Alias

Alias is needed to override the field name in the structure used for load / dump.

from dataclasses import dataclass
from typing import Annotated
from serpyco_rs import Serializer
from serpyco_rs.metadata import Alias

@dataclass
class A:
    foo: Annotated[int, Alias('bar')]

ser = Serializer(A)

print(ser.load({'bar': 1}))
>> A(foo=1)

print(ser.dump(A(foo=1)))
>> {'bar': 1}

FiledFormat

Used to have response bodies in camelCase while keeping your python code in snake_case.

from dataclasses import dataclass
from typing import Annotated
from serpyco_rs import Serializer
from serpyco_rs.metadata import CamelCase, NoFormat

@dataclass
class B:
    buz_filed: str

@dataclass
class A:
    foo_filed: int
    bar_filed: Annotated[B, NoFormat]

ser = Serializer(Annotated[A, CamelCase])  # or ser = Serializer(A, camelcase_fields=True)

print(ser.dump(A(foo_filed=1, bar_filed=B(buz_filed='123'))))
>> {'fooFiled': 1, 'barFiled': {'buz_filed': '123'}}

print(ser.load({'fooFiled': 1, 'barFiled': {'buz_filed': '123'}}))
>> A(foo_filed=1, bar_filed=B(buz_filed='123'))

NoneFormat

Via OmitNone we can drop None values for non required fields in the serialized dicts

from dataclasses import dataclass
from serpyco_rs import Serializer

@dataclass
class A:
    required_val: bool | None
    optional_val: bool | None = None

ser = Serializer(A, omit_none=True) # or Serializer(Annotated[A, OmitNone])

print(ser.dump(A(required_val=None, optional_val=None)))
>>> {'required_val': None}

Tagged unions

Supports tagged joins with discriminator field.

All classes in the union must be dataclasses or attrs with discriminator field Literal[str].

The discriminator field is always mandatory.

from typing import Annotated, Literal
from dataclasses import dataclass
from serpyco_rs import Serializer
from serpyco_rs.metadata import Discriminator

@dataclass
class Foo:
    type: Literal['foo']
    value: int

@dataclass(kw_only=True)
class Bar:
    type: Literal['bar'] = 'bar'
    value: str

ser = Serializer(list[Annotated[Foo | Bar, Discriminator('type')]])

print(ser.load([{'type': 'foo', 'value': 1}, {'type': 'bar', 'value': 'buz'}]))
>>> [Foo(type='foo', value=1), Bar(type='bar', value='buz')]

Min / Max

Supported for int / float / Decimal types and only for validation on load.

from typing import Annotated
from serpyco_rs import Serializer
from serpyco_rs.metadata import Min, Max

ser = Serializer(Annotated[int, Min(1), Max(10)])

ser.load(123)
>> SchemaValidationError: [ErrorItem(message='123 is greater than the maximum of 10', instance_path='', schema_path='maximum')]

MinLength / MaxLength

MinLength / MaxLength can be used to restrict the length of loaded strings.

from typing import Annotated
from serpyco_rs import Serializer
from serpyco_rs.metadata import MinLength

ser = Serializer(Annotated[str, MinLength(5)])

ser.load("1234")
>> SchemaValidationError: [ErrorItem(message='"1234" is shorter than 5 characters', instance_path='', schema_path='minLength')]

Getting JSON Schema

serpyco-rs can generate JSON Schema for your dataclasses (Draft 2020-12).

from dataclasses import dataclass
from serpyco_rs import Serializer

@dataclass
class A:
    """Description of A"""
    foo: int
    bar: str

ser = Serializer(A)

print(ser.get_json_schema())
>> {
    '$schema': 'https://json-schema.org/draft/2020-12/schema', 
    '$ref': '#/components/schemas/A[no_format,keep_nones]', 
    'components': {
        'schemas': {
            'A[no_format,keep_nones]': {
                'properties': {
                    'foo': {'type': 'integer'}, 
                    'bar': {'type': 'string'}
                }, 
                'required': ['foo', 'bar'], 
                'type': 'object', 
                'description': 'Description of A'
            }
        }
    }
}

Custom encoders for fields

You can provide CustomEncoder with serialize and deserialize functions, or serialize_with and deserialize_with annotations.

from typing import Annotated
from dataclasses import dataclass
from serpyco_rs import Serializer
from serpyco_rs.metadata import CustomEncoder

@dataclass
class Foo:
    val: Annotated[str, CustomEncoder[str, str](serialize=str.upper, deserialize=str.lower)]

ser = Serializer(Foo)
val = ser.dump(Foo(val='bar'))
>> {'val': 'BAR'}
assert ser.load(val) == Foo(val='bar') 

Note: CustomEncoder has no effect to validation and JSON Schema generation.

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

serpyco_rs-0.10.0.tar.gz (41.0 kB view details)

Uploaded Source

Built Distributions

serpyco_rs-0.10.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.1 MB view details)

Uploaded PyPy manylinux: glibc 2.17+ x86-64

serpyco_rs-0.10.0-cp311-none-win_amd64.whl (173.1 kB view details)

Uploaded CPython 3.11 Windows x86-64

serpyco_rs-0.10.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.1 MB view details)

Uploaded CPython 3.11 manylinux: glibc 2.17+ x86-64

serpyco_rs-0.10.0-cp311-cp311-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl (573.1 kB view details)

Uploaded CPython 3.11 macOS 10.9+ universal2 (ARM64, x86-64) macOS 10.9+ x86-64 macOS 11.0+ ARM64

serpyco_rs-0.10.0-cp310-none-win_amd64.whl (173.1 kB view details)

Uploaded CPython 3.10 Windows x86-64

serpyco_rs-0.10.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.1 MB view details)

Uploaded CPython 3.10 manylinux: glibc 2.17+ x86-64

serpyco_rs-0.10.0-cp310-cp310-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl (573.1 kB view details)

Uploaded CPython 3.10 macOS 10.9+ universal2 (ARM64, x86-64) macOS 10.9+ x86-64 macOS 11.0+ ARM64

serpyco_rs-0.10.0-cp39-none-win_amd64.whl (173.4 kB view details)

Uploaded CPython 3.9 Windows x86-64

serpyco_rs-0.10.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.1 MB view details)

Uploaded CPython 3.9 manylinux: glibc 2.17+ x86-64

serpyco_rs-0.10.0-cp39-cp39-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl (573.7 kB view details)

Uploaded CPython 3.9 macOS 10.9+ universal2 (ARM64, x86-64) macOS 10.9+ x86-64 macOS 11.0+ ARM64

File details

Details for the file serpyco_rs-0.10.0.tar.gz.

File metadata

  • Download URL: serpyco_rs-0.10.0.tar.gz
  • Upload date:
  • Size: 41.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: maturin/0.14.17

File hashes

Hashes for serpyco_rs-0.10.0.tar.gz
Algorithm Hash digest
SHA256 4b99ae99b45561cda32bdd0230e0429d9f39925230611afbed71602959ab6945
MD5 2abcc5a364a0eeaa7ccdca19db18645f
BLAKE2b-256 495213583fc96e2c9a36ec92bb86858d7ead9a727db5575c51fc9ed1f99882b0

See more details on using hashes here.

File details

Details for the file serpyco_rs-0.10.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for serpyco_rs-0.10.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 20ac04aecbc195cf73f55113d2117c6ca6410178ca71ca24a5f0d2decda857a1
MD5 a587b6bd7c968c2afcafcab83e9cb9d9
BLAKE2b-256 5e8c844a6fdd19e5387ba105b3487fe49ed765647cea8ead06d53512d5a3b7a8

See more details on using hashes here.

File details

Details for the file serpyco_rs-0.10.0-cp311-none-win_amd64.whl.

File metadata

File hashes

Hashes for serpyco_rs-0.10.0-cp311-none-win_amd64.whl
Algorithm Hash digest
SHA256 40aab0c4c39bc44f98b25e2f1deb4e0ff8d3df8e8510e39e32c084cdf3829615
MD5 e8795a01559063aa48cdab1fdc4f5f36
BLAKE2b-256 06c62f93547d26069e391270f52250675515603919cef79863aea1956b7e14e5

See more details on using hashes here.

File details

Details for the file serpyco_rs-0.10.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for serpyco_rs-0.10.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 f91b014148a6d5aaacebfa741bd7b90cb7024a9aff9397b1557c90020fa54571
MD5 015a0d0e86044957f269492f5cfefe23
BLAKE2b-256 9fd7f6ef51357f25344a021cf189c1736661e79bca0d7e40fe1f30d8b1ec88e0

See more details on using hashes here.

File details

Details for the file serpyco_rs-0.10.0-cp311-cp311-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl.

File metadata

File hashes

Hashes for serpyco_rs-0.10.0-cp311-cp311-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl
Algorithm Hash digest
SHA256 d40a46cf0e5ccbf8e1b9858b7dc2fb3b8bf059786caddc22e5bc353c4600b15a
MD5 9dfc68ca4d95e23fc779efe7655d5e2b
BLAKE2b-256 6ff14ed6179a89a4a9d71d8f63e92c75bf50b92352f2f58575ac240856eb8cde

See more details on using hashes here.

File details

Details for the file serpyco_rs-0.10.0-cp310-none-win_amd64.whl.

File metadata

File hashes

Hashes for serpyco_rs-0.10.0-cp310-none-win_amd64.whl
Algorithm Hash digest
SHA256 3350ef91abbbdfc7c4667af24b89acef1ac00cce4620714c1c93bfc62bc00d09
MD5 28412427aa8f9726403c8c9921c617ac
BLAKE2b-256 e6d6f04f574056c7e575ac1b01c3d3645d444fe0415bbaecec414a134a3a7474

See more details on using hashes here.

File details

Details for the file serpyco_rs-0.10.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for serpyco_rs-0.10.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 20cb1dc7b542c7edc9c3f841d3f6ae7c4b0e0f30f036475b863bf6d05aeb57ad
MD5 ee64fadd57a65fe1bca0ec01108f0b82
BLAKE2b-256 fca4c1f05ccdc00175d61204dea496a86483e797e27e1e8f020e2b2ae215bc4a

See more details on using hashes here.

File details

Details for the file serpyco_rs-0.10.0-cp310-cp310-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl.

File metadata

File hashes

Hashes for serpyco_rs-0.10.0-cp310-cp310-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl
Algorithm Hash digest
SHA256 0a28f2cc2cc79bc545214378132102f42bf137fa08b6af78f2568169dc2ff5ae
MD5 ceef812640c2c401cdc61097ce87aec3
BLAKE2b-256 796e6b89301ffb0bf18615286e8f0fa1ff748d8fb8ac79d5840d6311c614da31

See more details on using hashes here.

File details

Details for the file serpyco_rs-0.10.0-cp39-none-win_amd64.whl.

File metadata

File hashes

Hashes for serpyco_rs-0.10.0-cp39-none-win_amd64.whl
Algorithm Hash digest
SHA256 a069c1959773ad25336963b99942e854e033da0156f490e1f9ef3057e51afe00
MD5 2e64b5886d2332aa5234be3c41989228
BLAKE2b-256 f9914e4c7b7fdba0031286a0281ebe4bf38c28eb4519d60b80b37ddf5f50963a

See more details on using hashes here.

File details

Details for the file serpyco_rs-0.10.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for serpyco_rs-0.10.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 bbd512cad9a1474d9b60b9e2f7c5cdbe90f4dbe7844898d051dbadf6df9d8959
MD5 f324b3b1ac43fb796b95b1f34170dd4b
BLAKE2b-256 1465352f2782a780ee03d46bf087177e4e94b11840a3f8439787fb6e119d8ebd

See more details on using hashes here.

File details

Details for the file serpyco_rs-0.10.0-cp39-cp39-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl.

File metadata

File hashes

Hashes for serpyco_rs-0.10.0-cp39-cp39-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl
Algorithm Hash digest
SHA256 32662ba9bfc91455c2ff15a3b71eac99cbf97bb8e73dbcb6d0b453a54096129a
MD5 553624b05418b015c66102d67bd62a16
BLAKE2b-256 9742d0869ad09c8fbf15d5ad8468d7e3ac90edd834ed8d8ab42129a14298f86f

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