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.14.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 235c5c0138816b6921e1ce159100a44458fc171eaf28dddca99d4a7823e701fc |
|
MD5 | d22be093b4401d913ac9bd7d9b24cdb3 |
|
BLAKE2b-256 | a7763060b13e5163ec106fdb9554bbdc1cccdf63bbb7d0669db9780da8a5ebe6 |
Hashes for serpyco_rs-0.14.0-cp311-none-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | d4568b5bb7a0321a90c1f066cd606df2bb2a0d2f30d1eb51eed996be87bc9b07 |
|
MD5 | b0aa712d0a6ed30b9b1c57edc402137a |
|
BLAKE2b-256 | b17b3e6764e7b72d701db4b6b490ef329c6dd63d18dd9a3c7f78be8c94fa0977 |
Hashes for serpyco_rs-0.14.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 2c8fc933ec5edd41d7b55527cadb17e5444dba4b7763eca94ecf5193eb2fa433 |
|
MD5 | dc00a8ec1f91fc0f317a6db877da4e17 |
|
BLAKE2b-256 | e3c39791dbb16cdf3c264fad4a27a7bf293e60112cb3a83444a78c47fb0c8b05 |
Hashes for serpyco_rs-0.14.0-cp311-cp311-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 20ac7de420bc650ca72a4afb618903b0ed7fbf2d447d95827eeaae4660221360 |
|
MD5 | df8372526cc1f2cf69e677023033119e |
|
BLAKE2b-256 | a001b5610ab7e160ed9ddb1676e551c1d50907a99a4eb2cc2069b616202f5e32 |
Hashes for serpyco_rs-0.14.0-cp310-none-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | cc82a849c18863fbe90b3019bb7d7924946c88dca1e99a1e2e9d6233f13bcf12 |
|
MD5 | 61b6b825e197d2c644f9f479df12b85a |
|
BLAKE2b-256 | 74941770b864c5592efb4a19b066af2df71ff04862c4ff7fbfb19c9f82c7755c |
Hashes for serpyco_rs-0.14.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | cd06855fdc0e905ad4c8e39f1d6563b1ab764c75fc732157406f6872f0dda406 |
|
MD5 | 15c1fcbfca2c7472b6ffc34c6bf91584 |
|
BLAKE2b-256 | 2e3ec2cb0c40058afb98305a01b05f0b2f26ece4d47af817f90c986c080b721d |
Hashes for serpyco_rs-0.14.0-cp310-cp310-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | fbe26247f70a5f4a5749c5f4719566ea5e09c00171c0881ae6441cdd59b53f94 |
|
MD5 | 725c15dc6046ec6dc9eed1b3c63081af |
|
BLAKE2b-256 | ccf424ba789ca9030446773a31ce39828c9e5a72b95668ac062011254b63df52 |
Hashes for serpyco_rs-0.14.0-cp39-none-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | b1794f22d24694a5557b7ccf9c8a5684680bf1f49f054640acefeb0a08afa2fd |
|
MD5 | c7cb8aa417d160df31a65a000053cf7f |
|
BLAKE2b-256 | d68ac85bb8049c37fb3d3e2610371da62f139fabb312ab22788d9e51b06eb282 |
Hashes for serpyco_rs-0.14.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | c282334a9f6c4f75abf764a0afeffb6c63c5405c338f2c9554657225674efe8f |
|
MD5 | 07b467269c26617bfeaacaf151b45962 |
|
BLAKE2b-256 | d942064177036ed87b9065e5ca0a5298ec01c93dc35699d21ab4afb92e2c8fe1 |
Hashes for serpyco_rs-0.14.0-cp39-cp39-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 826fe86b748ca793346473e193560c4e5c824658777e67417d24df0eea7b5d26 |
|
MD5 | 30ca7819904f314b9bb36241faa8c69b |
|
BLAKE2b-256 | 101e7db6b24aed04df6ab7ff4a9abb722cbc70332f8d27bfa67872e0f273ac90 |