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
- TypedDict
- 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
- 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}
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')]
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='', schema_path='required')]
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.
Load data from raw json
serpyco-rs
can load data from raw json string.
Load data from raw json string is faster than [or]json.loads
+ Serializer.load
about 20%+.
This is possible because serpyco-rs
uses serde_json
to load data from a raw json string and avoids unnecessary conversion of python objects to serde_json::Value for validation process.
from dataclasses import dataclass
from serpyco_rs import Serializer
@dataclass
class A:
foo: int
bar: str
ser = Serializer(A)
print(ser.load_json('{"foo": 1, "bar": "buz"}'))
>> A(foo=1, bar='buz')
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-0.13.0-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 5f6efde718f3e89d6b29d552c0e02911f5019e3d1ac2a643f8a3e0599ff63abf |
|
MD5 | c2b534672b82f51497382727dc31f603 |
|
BLAKE2b-256 | dd4dce1d9ab9050479a07d397660aec6cc4cef8ef07c9f7c7fd9658a2bc77d1d |
Hashes for serpyco_rs-0.13.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | b0d0d3aab5fcf7fdd74f09cabdeb0fa33d6b435fb8649c191feff7ebdba17ca9 |
|
MD5 | a5b814c7a6ece8a8df59b8c26032208c |
|
BLAKE2b-256 | f43e7ef092e4bb4e9b2ecf7abd20fa4514d7c64b2cf680859ce92dc87d32142b |
Hashes for serpyco_rs-0.13.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 05a6bdcb42a9d44dde4c21df7517c34a5b59ebea3dd56bfb64494361f11774d7 |
|
MD5 | 722e4d219044b302ab36fa0707bafcf2 |
|
BLAKE2b-256 | fce1dd44e5e16d6a6dcc69b899a65b13bee580cfd62ab0ffb74104f59d7e1e1c |
Hashes for serpyco_rs-0.13.0-cp311-none-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | de713e2ebc150b03cf6d4198b4e7a9fea792dbd5ca25cf47dc814d6257c61363 |
|
MD5 | 30e70900db6d00d086ffc86e8cd858e8 |
|
BLAKE2b-256 | 5582818d4a8010aefe1eb73781c675a7502167def7e5a7cbba9191af30e345b8 |
Hashes for serpyco_rs-0.13.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | a18240811df3543179e0051ec913dc97774c95143d08e1048f96d7fd6b54e1b2 |
|
MD5 | 0e55c6b2cad201f7328095b608df2493 |
|
BLAKE2b-256 | f65ef900f05b1a01df5509f4fd3f25ffbf3ccdc41d53a17b1adeb15e2ceb9558 |
Hashes for serpyco_rs-0.13.0-cp311-cp311-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | a36d0ac73fc689dd1e43aced870065feb04d5b442f41ca88e1dab37225db0f50 |
|
MD5 | b7144af9a43e1a7bb4aaa24e6be671b8 |
|
BLAKE2b-256 | 2cd49baff0a777fa9d52725e1211e00340d64421e9b852809dda4bacf407b95d |
Hashes for serpyco_rs-0.13.0-cp310-none-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | e74a8a677b6f98211dabc5c9a05a59447ddc6ff2aa0c0f68800bbe1761a5b6fd |
|
MD5 | fcea336093337e62d0267dfde67b084e |
|
BLAKE2b-256 | e35962fb7f4e16b16928cd3314c5d2f36e376aafac04f15d518d14dd58859537 |
Hashes for serpyco_rs-0.13.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 00eb1e9b7c5b3a2dcd68099483651f7ab18b7280cb61c06c90dbffb16b3ce99b |
|
MD5 | c1270c9ab105ea13304a4fb3c24dd6e1 |
|
BLAKE2b-256 | d386794269e6b7316ad8eb8f763aa00c1690b6f680b17089c71f64fd25638d74 |
Hashes for serpyco_rs-0.13.0-cp310-cp310-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 0a544e53c579500630a52a1272db9d2940bb3740ace6b4eb65a9f03e62163e67 |
|
MD5 | 94aa180e42925613461cd3a40d4277d9 |
|
BLAKE2b-256 | 1d33171591ad6237837f2353e8bf837cfef819fd1f7243fc3afbae7a860c95a0 |
Hashes for serpyco_rs-0.13.0-cp39-none-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | fcb4312f7daea9fda27c170b63fe98a12681dd6a9e41ed187dff9d3c0b997396 |
|
MD5 | 959d3ca177103635a6991d2336e0f92a |
|
BLAKE2b-256 | bf28ea9452e2b1219bd0c7174e008bf7173e67086f51af5037dffe75ca6b0f71 |
Hashes for serpyco_rs-0.13.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8971cf45704e538dbaa91793834fc2efddf89498b86af80c9847ae16b0e0a827 |
|
MD5 | 3520bf772af3a9097de279ac73f99e16 |
|
BLAKE2b-256 | b5e99ad16e086c4e0491d3a5e69f236b9b0a9a3ec5ff8fc0d901b041c7cc1ac0 |
Hashes for serpyco_rs-0.13.0-cp39-cp39-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | fcf542b4937330bcc62ae3c07175d1ddc04f9abbcee543da846975ba221d3eb8 |
|
MD5 | 5571aafb715b023d142f7a404bdb5dc9 |
|
BLAKE2b-256 | 7ab78b7cfe23d8af5b9cd9f98965663d07cedcbd3dfe140b60d97d4eeff855ec |