Skip to main content

Pydantic support for the sortedcontainers package.

Project description

sortedcontainers-pydantic

PyPI Supported Python versions tests codecov

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sortedcontainers_pydantic-1.0.0.tar.gz (8.2 kB view hashes)

Uploaded Source

Built Distribution

sortedcontainers_pydantic-1.0.0-py3-none-any.whl (4.6 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page