Published
Pydantic support for the sortedcontainers package.
pip install sortedcontainers-pydantic
Package Downloads
Project URLs
Requires Python
>=3.8
sortedcontainers-pydantic
This package adds Pydantic support to sortedcontainers, a fast pure-Python library for sorted mutable collections.
It implements Pydantic's special methods on subclasses of sortedcontainer's SortedDict
, SortedList
, and SortedSet
classes so that you can use them with Pydantic's models, validation, and serialization. To use, simply import the respective class of the same name from sortedcontainers_pydantic
instead of from sortedcontainers
. Only Pydantic V2 is supported.
from pydantic import BaseModel, TypeAdapter
from sortedcontainers_pydantic import SortedList
class MyModel(BaseModel):
sorted_list: SortedList[int]
MyModel(sorted_list=[3, 1, 2])
#> MyModel(sorted_list=SortedList([1, 2, 3]))
MyModel.model_validate_json('{"sorted_list": [3, 1, 2]}')
#> MyModel(sorted_list=SortedList([1, 2, 3]))
MyModel(sorted_list=[3, 1, 2]).model_dump_json()
#> '{"sorted_list":[1,2,3]}'
TypeAdapter(SortedList).validate_python([3, 1, 2])
#> SortedList([1, 2, 3])
TypeAdapter(SortedList).validate_json("[3, 1, 2]")
#> SortedList([1, 2, 3])
Reproducible example created by reprexlite v0.5.0
Installation
sortedcontainers-pydantic is available on PyPI. You can install it with
pip install sortedcontainers-pydantic