Skip to main content

Pydantic Cache

Cache results of Python functions, with support for serialization of rich data types powered by Pydantic.

Supports caching to disk or Redis by default, but additional caching backends can easily be added.

Examples

Basic usage

You can use any data types which can be serialized by Pydantic, both in the function signature (cache key) and the returned values:

from datetime import datetime, timedelta
from pydantic import BaseModel
from pydantic_cache import disk_cache

class MyModel(BaseModel):
    a: int
    b: datetime
    d: set[datetime]


@disk_cache(path="~/.cache/my-function", ttl=timedelta(days=1))
def my_function(date: datetime) -> list[MyModel]:
    return []  # Some expensive computation

In the above example, subsequent calls to the function with the same argument will fetch the results from the cache on disk. Serialization and deserialization are handled based on the function's type annotations.

Redis support

The library includes support for caching results to/from redis. This depends on redis, which can be installed via pip install pydantic-cache[redis].

from datetime import timedelta
from pydantic_cache import cache
from pydantic_cache.backend import RedisBackend
from redis import Redis

redis = Redis(...)

@cache(RedisBackend(redis, ttl=timedelta(days=1)))
def my_function() -> dict:
    return {}

Custom cache backends

You can implement custom cache backends by sub-classing Backend:

from pydantic_cache import Backend, cache


class MemoryBackend(Backend):
    def __init__(self) -> None:
        # Optional initial set-up of the backend.
        self._cache: dict[str, str] = {}

    def get(self, key: str) -> str:
        # Implement cache retrieval here.
        # Cache misses should raise a KeyError.
        return self._cache[key]

    def write(self, key: str, value: str) -> None:
        # Write to the cache here.
        self._cache[key] = value


@cache(backend=MemoryBackend)
def my_function() -> dict:
    return {}

Deferred backend resolution

Some backends may rely on reading configurations or creating connections to external services, which is best avoided at import time. To support this, the cache decorator optionally accepts a callable which returns the backend, instead of the backend itself.

from datetime import timedelta
from pathlib import Path
from pydantic_cache import DiskBackend, cache
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    cache_ttl: timedelta
    cache_path: Path


def get_cache_backend() -> DiskBackend:
    settings = Settings()
    return DiskBackend(settings.cache_path, ttl=settings.cache_ttl)


@cache(backend=get_cache_backend)
def my_function() -> dict:
    return {}

asyncio support

Asynchronous functions are supported by default, however using a synchronous backend will naturally result in blocking calls:

import asyncio
from pydantic_cache import DiskBackend, cache

@cache(backend=DiskBackend(...))
async def my_function() -> dict:
    return await asyncio.sleep(0, {})

To avoid blocking IO calls in the cache backend, you can implement an asynchronous backend as a subclass of AsyncBackend. See the following example using aioredis:

import asyncio
import aioredis
from pydantic_cache import AsyncBackend, cache


class AioRedisBackend(AsyncBackend):
    def __init__(self, redis: aioredis.Client) -> None:
        self.redis = redis

    async def get(self, key: str) -> str:
        result = await self.redis.get(key)
        if result is None:
            raise KeyError(key)
        return result

    async def write(self, key: str, value: str) -> None:
        await self.redis.set(key, value)


@cache(backend=AioRedisBackend(...))
async def my_function() -> dict:
    return await asyncio.sleep(0, {})

Installation

This project is not currently packaged and so must be installed manually.

Clone the project with the following command:

git clone https://github.com/jacksmith15/pydantic-cache.git

Development

Install dependencies:

pyenv shell 3.10.x
pre-commit install  # Configure commit hooks
poetry install  # Install Python dependencies

Run tests:

poetry run inv verify

License

This project is distributed under the MIT license.

Metadata

Release files for pydantic-cache 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pydantic-cache 0.1.0
File Size Uploaded Provenance Actions
pydantic_cache-0.1.0.tar.gz 5.4 kB Without provenance Details for pydantic_cache-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pydantic-cache 0.1.0
File Interpreter ABI Platform Actions
pydantic_cache-0.1.0-py3-none-any.whl Python 3 none any Details for pydantic_cache-0.1.0-py3-none-any.whl

Total release size: 12.2 kB

Release files / pydantic_cache-0.1.0.tar.gz

Download URL pydantic_cache-0.1.0.tar.gz
Size 5.4 kB
Tags Source
SHA-256 checksum
How to use checksums
8fe9be25b9d2f74308674590c363fa49c098a9eab26b2c11a7e736caebd7377c
BLAKE2b-256 checksum
How to use checksums
410cbc45a7d65945a123159e0fc2f18a82a030195dd72a19c76c6aaee1477e28
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.6.1 CPython/3.10.13 Linux/6.2.0-1019-azure

Release files / pydantic_cache-0.1.0-py3-none-any.whl

Download URL pydantic_cache-0.1.0-py3-none-any.whl
Size 6.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
393e7950061c5cfaf9b67dca9fced5dc8aa14f8c1f7ba5989b411ad19b5ceddb
BLAKE2b-256 checksum
How to use checksums
c809bc1fcb28b09540386412be469c5b889a321154c8abb4e1fa3233c2198eb8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.6.1 CPython/3.10.13 Linux/6.2.0-1019-azure

Security for pydantic-cache 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page