Skip to main content

Advanced serialization for Pydantic models

Project description

pydantic-cereal

Advanced serialization for Pydantic models

Pydantic is the most widely used data validation library for Python. It uses type hints/type annotations to define data models and has quite a nice "feel" to it. Pydantic V2 was released in June 2023 and brings many changes and improvements, including a new Rust-based engine for serializing and validating data.

This package, pydantic-cereal, is a small extension package that enables users to serialize Pydantic models with "arbitrary" (non-JSON-fiendly) types to "arbitrary" file-system-like locations. It uses fsspec to support generic file systems. Writing a custom writer (serializer) and reader (loader) with fsspec URIs is quite straightforward. You can also use universal-pathlib's UPath with pydantic-cereal.

📘 See the full documentation here. 📘

Usage Example

See the minimal pure-Python example to learn how to wrap your own type. Below is a preview of this example.

from fsspec import AbstractFileSystem
from pydantic import BaseModel, ConfigDict

from pydantic_cereal import Cereal

cereal = Cereal()  # This is a global variable


# Create and "register" a custom type

class MyType(object):
    """My custom type, which isn't a Pydantic model."""

    def __init__(self, value: str):
        self.value = str(value)

    def __repr__(self) -> str:
        return f"MyType({self.value})"


def my_reader(fs: AbstractFileSystem, path: str) -> MyType:
    """Read a MyType from an fsspec URI."""
    return MyType(value=fs.read_text(path))  # type: ignore


def my_writer(obj: MyType, fs: AbstractFileSystem, path: str) -> None:
    """Write a MyType object to an fsspec URI."""
    fs.write_text(path, obj.value)

MyWrappedType = cereal.wrap_type(MyType, reader=my_reader, writer=my_writer)


# Use type within Pydantic model

class MyModel(BaseModel):
    """My custom Pydantic model."""

    config = ConfigDict(arbitrary_types_allowed=True)  # Pydantic configuration
    fld: MyWrappedType


mdl = MyModel(fld=MyType("my_field"))

# We can save the whole model to an fsspec URI, such as this MemoryFileSystem
uri = "memory://my_model"
cereal.write_model(mdl, uri)

# And we can read it back later
obj = cereal.read_model(uri)
assert isinstance(obj, MyModel)
assert isinstance(obj.fld, MyType)

For wrapping 3rd-party libraries, see the Pandas dataframe example.

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

pydantic-cereal-0.0.6.tar.gz (25.1 kB view details)

Uploaded Source

Built Distribution

pydantic_cereal-0.0.6-py3-none-any.whl (13.6 kB view details)

Uploaded Python 3

File details

Details for the file pydantic-cereal-0.0.6.tar.gz.

File metadata

  • Download URL: pydantic-cereal-0.0.6.tar.gz
  • Upload date:
  • Size: 25.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/4.0.2 CPython/3.11.8

File hashes

Hashes for pydantic-cereal-0.0.6.tar.gz
Algorithm Hash digest
SHA256 aac44edc80de142706f765eb550b241e7be16ced713cea2f2fc981d248a8fdca
MD5 ff3f3295ab9d1ae0fe4872a396701dfd
BLAKE2b-256 33843c67e76d3d77f2603a2598150e0ebabe2fb380c8552d4e727b333fcec3ce

See more details on using hashes here.

File details

Details for the file pydantic_cereal-0.0.6-py3-none-any.whl.

File metadata

File hashes

Hashes for pydantic_cereal-0.0.6-py3-none-any.whl
Algorithm Hash digest
SHA256 334ecc669687a415e1bb02c943393def6401b32d001fb2c7313f2923c439874b
MD5 2f1a67f8ab497207efea34596cda5981
BLAKE2b-256 33daec4811d5b21ff2b54f126265a2c6cdae65c6faed69b86fa7705e0556a95e

See more details on using hashes here.

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