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']}
Inspired by serpyco.
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 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
- Bytes (pass through)
- TypedDict
- Mapping
- Sequence
- Tuple (fixed size)
- Literal[str, ...]
- Tagged unions (restricted)
Benchmarks
Linux
Load
Library | Median latency (milliseconds) | Operations per second | Relative (latency) |
---|---|---|---|
serpyco_rs | 0.16 | 6318.1 | 1 |
mashumaro | 0.45 | 2244.4 | 2.81 |
pydantic | 0.57 | 1753.9 | 3.56 |
serpyco | 0.82 | 1228.3 | 5.17 |
marshmallow | 8.49 | 117.4 | 53.35 |
Dump
Library | Median latency (milliseconds) | Operations per second | Relative (latency) |
---|---|---|---|
serpyco_rs | 0.07 | 13798 | 1 |
serpyco | 0.07 | 13622 | 1.02 |
mashumaro | 0.1 | 10219.5 | 1.36 |
pydantic | 0.22 | 4615.5 | 2.99 |
marshmallow | 2 | 497 | 27.69 |
MacOS
macOS Monterey / Apple M1 Pro / 16GB RAM / Python 3.11.0Load
Library | Median latency (milliseconds) | Operations per second | Relative (latency) |
---|---|---|---|
serpyco_rs | 0.1 | 9865.1 | 1 |
mashumaro | 0.2 | 4968 | 2 |
pydantic | 0.34 | 2866.7 | 3.42 |
serpyco | 0.69 | 1444.1 | 6.87 |
marshmallow | 4.14 | 241.8 | 41.05 |
Dump
Library | Median latency (milliseconds) | Operations per second | Relative (latency) |
---|---|---|---|
serpyco_rs | 0.04 | 22602.6 | 1 |
serpyco | 0.05 | 21232.9 | 1.06 |
mashumaro | 0.06 | 15903.4 | 1.42 |
pydantic | 0.16 | 6262.6 | 3.61 |
marshmallow | 1.04 | 962 | 23.5 |
Supported annotations
serpyco-rs
supports changing load/dump behavior with typing.Annotated
.
Currently available:
- Alias
- FieldFormat (CamelCase / NoFormat)
- NoneFormat (OmitNone / KeepNone)
- Discriminator
- Min / Max
- MinLength / MaxLength
- CustomEncoder
- NoneAsDefaultForOptional (ForceDefaultForOptional)
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}
FieldFormat
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='')]
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='')]
NoneAsDefaultForOptional
ForceDefaultForOptional
/ KeepDefaultForOptional
can be used to set None as default value for optional (nullable) fields.
from dataclasses import dataclass
from serpyco_rs import Serializer
@dataclass
class Foo:
val: int # not nullable + required
val1: int | None # nullable + required
val2: int | None = None # nullable + not required
ser_force_default = Serializer(Foo, force_default_for_optional=True) # or Serializer(Annotated[Foo, ForceDefaultForOptional])
ser = Serializer(Foo)
# all fields except val are optional and nullable
assert ser_force_default.load({'val': 1}) == Foo(val=1, val1=None, val2=None)
# val1 field is required and nullable and val1 should be present in the dict
ser.load({'val': 1})
>> SchemaValidationError: [ErrorItem(message='"val1" is a required property', instance_path='')]
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.
Bytes fields
serpyco-rs
can loads bytes fields as is (without base64 encoding and validation).
from dataclasses import dataclass
from serpyco_rs import Serializer
@dataclass
class Foo:
val: bytes
ser = Serializer(Foo)
ser.load({'val': b'123'}) == Foo(val=b'123')
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'
}
}
}
}
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-1.0.1-cp312-none-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | bd31fb73cf581587c113b90fe0a00ae7d5394d626866bef0492f59048f03c894 |
|
MD5 | d40e1644682267c3c5068715bea5f01c |
|
BLAKE2b-256 | 8a94ffd76ca771f034e2176b12e9bfb4fe92efc8f2b281c1e11a96e40e1877a2 |
Hashes for serpyco_rs-1.0.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | c1c1ffa576ff8b21e944fb020663f56aeda8c80c11cbed223e7d1d76d4b83698 |
|
MD5 | a5f2610677eab998804832f194bbabb9 |
|
BLAKE2b-256 | 58382fd205a79f64564d58ed50686d18def86e3f7d0687ec38ff44e87664ec00 |
Hashes for serpyco_rs-1.0.1-cp312-cp312-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | ea3a036b7d26997a11189af37bbb24414956ec1da1ed69d899fe72dc730cbb6e |
|
MD5 | 82bd2b87189c66502b2cbc1386dc5aeb |
|
BLAKE2b-256 | fe75fe1698495929c5060afebc9f5876676ebcd0bfbcd5e186b58da4e8d9bb6d |
Hashes for serpyco_rs-1.0.1-cp311-none-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 195151fcc73ad7655080de3068dcb564c7cd4cca79d1275ce3fcc5adf8f10e16 |
|
MD5 | 7fdb0722156770769f3aaeef1af39300 |
|
BLAKE2b-256 | b6b616c3fde3d9ee62137cbbd16682f8c5060354d62356ba1d7175764e707616 |
Hashes for serpyco_rs-1.0.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | d7ae86691ed420a408ab033c36c2813c029730f14cdfa2414f2154f52bd9b10c |
|
MD5 | 61458c18435186398afab0a1f9d5688a |
|
BLAKE2b-256 | 9574dc2b8d0f96320e04f41e161cfb5ecc3b243fe80be1988f4953d1130b8875 |
Hashes for serpyco_rs-1.0.1-cp311-cp311-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | c688f9a4d82017e653bc5b8553e116e25355a96e5a047d7eed046755159e5b28 |
|
MD5 | 68426a55b1ea9379ef5638a594997794 |
|
BLAKE2b-256 | 9681de81cbf51d2fffdccdacc902bc61d2895143d60a3dbaa6eab8b180785c1e |
Hashes for serpyco_rs-1.0.1-cp310-none-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | a7c0a4eb9cd6ccf255fa2cb726f21d6cff9c8b9dc7470f26f0ac82880416375c |
|
MD5 | c40918c7b874ec95b1179f2038e1542a |
|
BLAKE2b-256 | b3c6bb2c005d74310c33846f40537d8c819b267fe3d173397d80a88fafb3c5cd |
Hashes for serpyco_rs-1.0.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | b66b052b1b114ce6e2ac4c8dd9ed87345e932e7aa6657f59d9ce44719bddb8f9 |
|
MD5 | 461bfb505121db7c309027e85427987d |
|
BLAKE2b-256 | 466d934a4e3488d2f6e0df8555db8b44d6d016a69e660917a0875f093ead482e |
Hashes for serpyco_rs-1.0.1-cp310-cp310-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 3a626c16697ef808921496a6d8463ef940707809513e39321b1332a0c1763f7c |
|
MD5 | 11b6be489dc910a66e2e3ac0bd0d22d1 |
|
BLAKE2b-256 | cf364d2688848cafabf0ac5c305729556040757c8a44e8514cffea56ac1b4ee9 |
Hashes for serpyco_rs-1.0.1-cp39-none-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 69e41bb1f9f386ed61c820e7cee3c333a9070db63923d1431817d678c16a5789 |
|
MD5 | 1f49b6ad4b7bf7d642f3fbd9725461b3 |
|
BLAKE2b-256 | 5104b90d65b8de6b02e93dc5311626d2f249e5861afe77dd701dd8bb67a4a643 |
Hashes for serpyco_rs-1.0.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 91ef3a89fd5587083ea2bee827d369277f29e3f6e8d295592fa9c7b1117a787c |
|
MD5 | 384ed3eba7da24aa9291273e35c1b01c |
|
BLAKE2b-256 | a220488b01830dfdee21e75f42974c10fbcea6ea5c60282cdaf56ef2b3129606 |
Hashes for serpyco_rs-1.0.1-cp39-cp39-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 2f91eb7129136ccbb4fe5fa067cda07c210639c6cc2ef2b59458f78f362352cc |
|
MD5 | b0e08102a5eeaad048361e0c2174f0c4 |
|
BLAKE2b-256 | fb7157dd83f5123c6e43714f88e63774f6c14a35cda49fadd6608d61dbf9f19e |