No project description provided
Project description
serpyco-rs: a serializer for python dataclasses
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
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
Built Distributions
Hashes for serpyco_rs-0.9.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 811b62393a6e07e7941e6cf6dd5a77c404c8771b40ee0248b8b80f1e1c9341d3 |
|
MD5 | d8ff55012c4aaef2dcdfff887d4d40bb |
|
BLAKE2b-256 | c043b1776018b4aa7547429b1d79faf10179732b4d8911036af2bc039b321ef9 |
Hashes for serpyco_rs-0.9.0-cp311-none-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 89195622a0053ce5df4f636dce29caa827cbf873ea44de0f0e54f984809b9b26 |
|
MD5 | 39d516e6b8d1913abb082ea1828bf523 |
|
BLAKE2b-256 | f3f3d0ad528b31ec7ac45c91a6a544faa0afc70ee444f58c24b1febb4189c442 |
Hashes for serpyco_rs-0.9.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | b08862662f732d5094438602272b09646b59399d5abbb7d434df21d00a04ea66 |
|
MD5 | a20192fb0e7e8ec23531dffbdd8abd70 |
|
BLAKE2b-256 | d475abebae7c984ea8b25a2eff8240f9bf8d9897f91092afdf74340609cf0908 |
Hashes for serpyco_rs-0.9.0-cp311-cp311-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 05a7c2d75b5e9f61eaea2a929404ee83b3863ec0a8b575b690faac7eed4a50de |
|
MD5 | 93da2f3656079232feb92ba46a05d885 |
|
BLAKE2b-256 | a1528ec07f134e867ac039b6561233a2a516f3576b5e04c43d2f6e3e780003f9 |
Hashes for serpyco_rs-0.9.0-cp310-none-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 28dc337e3abac90dd80b3e43c3f0f7f3820b8f7dc63b10e13567577ea17c7273 |
|
MD5 | 7c1cc6d3c5e6c36b4777faf01c39cf95 |
|
BLAKE2b-256 | 6baa479842de420dc1b4e464b14b3c16a3205c7edee9083488c29cfd92a59040 |
Hashes for serpyco_rs-0.9.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | d830f025d3bf6c53226a8da58bb238ffc94cf5686a0b4d5145686d67caa2a7ae |
|
MD5 | 2927d32161c367c7e5c7e1d4bfd14a33 |
|
BLAKE2b-256 | 3df4891f421eb256a9c7e03446121f9e93ead224feee8c55910766484a5b405a |
Hashes for serpyco_rs-0.9.0-cp310-cp310-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 964e05db03d2654e1dfaae79cb4a8d3a2b90c2bc8378061d7820d778dea4a0c9 |
|
MD5 | b740e253eb65004d91adde39911c92ca |
|
BLAKE2b-256 | 98043121e0d8ef45fd48bed0c9ce1c84b7c494d9329d133bd014b5de221f3d59 |
Hashes for serpyco_rs-0.9.0-cp39-none-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 691d6d4c3c8554ba7dce67a00c5d2573dcd9949aa409db3b5ba5a0c2215fa2c1 |
|
MD5 | b1ddf0212f5db6fd0f06b13ab4a91ccd |
|
BLAKE2b-256 | 0ca3998412529088e15ec00ad344ba9f088337d563273c54140331341a658401 |
Hashes for serpyco_rs-0.9.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | fd4a9eed0adfc13e502a9a1200cc9a71d7cce7012660172e40fb710fa8881276 |
|
MD5 | 6dba561c62353c0fda53243f8983b7ee |
|
BLAKE2b-256 | aacc2662e5b5b0c1daeff2187a1881575957aa4929511146b75a72b4075b1741 |
Hashes for serpyco_rs-0.9.0-cp39-cp39-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8493267de3c5d98a9f4f38d4926c8aaeddb1ecdc9c67fe7915db4d11d8a5a3e0 |
|
MD5 | 9b3abafbbd8142595a91f04d27586ada |
|
BLAKE2b-256 | cdb414f85b374bd5ccd95d978c8be52d9f9fe23790816e8011194475120f3757 |