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 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
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')]
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.
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.12.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 0fd2fb6a741382d6eb4634b4d309e95bc756a430c85cb92abf40339a83d96b36 |
|
MD5 | 38c006422a9fe45c4c78aceb2ab101f8 |
|
BLAKE2b-256 | 27238845a1726d73024e0648a5557200200111a48371ab6532f0608da097d798 |
Hashes for serpyco_rs-0.12.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | e380ea4091a0c8f4aefc26401cc14c7de90844f6d18a48600d491361679243e2 |
|
MD5 | c71c634d271e50734e15b8e4b62d5085 |
|
BLAKE2b-256 | 020b3c28d87d018eee4c8f653372b6a2787d86433854af7667daf8196d5cba6d |
Hashes for serpyco_rs-0.12.0-cp311-none-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 26295ce4d6491d658fea80bc635e4b8927b3728001c21b93e97f3fa632041ccf |
|
MD5 | 001fe6a0f4e58730ede86f0dbb267e6f |
|
BLAKE2b-256 | 422255107c641179d8840de3cb61620ce80d1e23ab26b40f4fb5a69c8bd9a837 |
Hashes for serpyco_rs-0.12.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 37dd94eb9bf13f4e62b8c99da434545938fe84e8b7d1049825888a6e6299d8f0 |
|
MD5 | e184f7dd969751e6949a826737b28736 |
|
BLAKE2b-256 | a167889728015383d7ff50cdb88141cec64bc863577d268fdbaacdfd2821475f |
Hashes for serpyco_rs-0.12.0-cp311-cp311-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 84984d4610648dcf6214f44fd32c1237deb1a95dcb2acd7c7f373e3c62687fea |
|
MD5 | 9db49162c16bfaf398be0894bc765748 |
|
BLAKE2b-256 | 4e942a9cfaf7e9eeb282d954fd76afd50c297e0fdce27ed36f7ef87f7bdf8fef |
Hashes for serpyco_rs-0.12.0-cp310-none-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 4ed7d52b9d90e83252293a91eafef453008e0bf98ee31f1a24ebc4e9eea2749e |
|
MD5 | f6afd2abf539c1edf380af7a9dfc4db3 |
|
BLAKE2b-256 | 86e70b869ed2c743c0944f5c83d2ffb78a2a672ed6fec982456746d85695b308 |
Hashes for serpyco_rs-0.12.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 2ce42fa02b3421c0b9e852eacfc2883733dfe7a036dee9824a1815fb90eb81fb |
|
MD5 | 40342b7973823b627579b5b2998b0934 |
|
BLAKE2b-256 | bf1c9c1543812a89459178264bc78b6e3fde957cfae7e58a4abe2f253ad45ce8 |
Hashes for serpyco_rs-0.12.0-cp310-cp310-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 0e8a9a8dc9c5819de07d537267d1c9bbac05f05cdec785448f346a8862971ebb |
|
MD5 | 2581a294a14ec95263c47053f22a9931 |
|
BLAKE2b-256 | 8e1fcac3313da0e226fb21d8485394fafdd567f1b1a8daf07fe064e54ed271fc |
Hashes for serpyco_rs-0.12.0-cp39-none-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9b831bdba640e21b4722cdb4d3b414d05c0f7c943407fd0362d05725c33c9d7a |
|
MD5 | 3b32e8cc9ef7d66d96be410345dae8b0 |
|
BLAKE2b-256 | 4f149ed6707f30b1b046bf252d37c97a60e5f7a63bb5101d6f7eba944fa68d72 |
Hashes for serpyco_rs-0.12.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | ed5ccb9f3e4afe4500df1fdb387074b103af70108d399722ba56dca1230e3946 |
|
MD5 | fb7f5b28a71d1ce9569ba8dd98bb0cad |
|
BLAKE2b-256 | 0c379c640a069661de9d84f036f870db91001f5a0cd33e3b75f4d9953f06728b |
Hashes for serpyco_rs-0.12.0-cp39-cp39-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | acb080d37f33daa9e5cb359d4b22bef24e10e67878bc30ac66b7353031e9457e |
|
MD5 | 44b5688885fd8a7beb98cec5a6324e24 |
|
BLAKE2b-256 | d5f950cfebbe3b728f227e25f4cacfd694b7582591d8b629e020206db7ac1f53 |