Skip to main content

pydantic-cacheable-model

Small helpers to make your Pydantic v2 models trivially cacheable to disk.


Installation

pip install pydantic-cacheable-model

Supports Python 3.10+


Usage

from __future__ import annotations
from datetime import datetime
from pydantic_cacheable_model import CacheableModel, CacheKey

class UserModel(CacheableModel):
    email: CacheKey[str]  # <- used as the cache key
    joined: datetime

# Create and cache to disk
u = UserModel(email="alice@example.com", joined=datetime.now())
u.cache()

# Load a single item by key
u2 = UserModel.load(cache_key="alice@example.com")
assert u2 == u

# Optionally handle missing caches or validation mismatches
maybe_user = UserModel.load(cache_key="missing@example.com", not_found_ok=True)

# List everything cached
all_users = UserModel.load_all_cached()

Configuration

Below are the configuration knobs you can use. This single block shows all options; pick the ones you need.

from __future__ import annotations
from datetime import datetime
from pydantic_cacheable_model import CacheableModel, CacheKey

# 1) Customize cache root and directory name
class UserModel(CacheableModel):
    # Change root directory (default: ".cache")
    CACHE_ROOT = ".data-cache"

    # Force a specific subdirectory name (otherwise derived from class name)
    CACHE_DIRNAME = "users"

    email: CacheKey[str]
    joined: datetime


# 2) Customize filename mapping (avoid if ids contain unsafe characters)
class FriendlyFilenames(CacheableModel):
    slug: CacheKey[str]

    @classmethod
    def cache_key_to_filename(cls, *, cache_key: str) -> str:
        # Default uses a SHA-256 hash; this stores plain ids instead
        return f"{cache_key}.json"


# 3) Custom key logic without using CacheKey
class Document(CacheableModel):
    kind: str
    slug: str

    @property
    def cache_key(self) -> str:
        return f"{self.kind}/{self.slug}"

How It Works

  • Cache location: ./.cache/<model-dir>/ by default. <model-dir> is derived from the class name, removing a trailing Model and converting CamelCase to kebab-case (e.g., UserModel → user, LongNameModel → long-name).
  • File naming: sha256(cache_key).json for safe, stable filenames.
  • Data format: pretty-printed JSON. Enum values and datetime objects serialize automatically.
  • Choosing the key: mark one field with CacheKey[T]. If you need custom logic, override the cache_key property instead.

API

  • CACHE_ROOT: str — class var; default ".cache".
  • CACHE_DIRNAME: str | None — class var; override to force subdirectory name. If None, derived from the class name.
  • cache_dir_path() -> str — directory path where this model caches files.
  • cache_key_to_filename(*, cache_key: str) -> str — classmethod; maps a key to a filename (default: SHA-256 hex + .json).
  • get_cache_path(*, cache_key: str) -> str — full path to the cache file for a given key.
  • load(*, cache_key: str, not_found_ok: bool = False, warn_mismatch: bool = True) -> Self | None — load and validate. If not_found_ok=True, returns None on missing or, when validation fails, returns None and optionally warns.
  • load_all_cached() -> list[Self] — load all cached instances for the model.
  • cache() -> None — write the instance to disk.
  • cache_path: str — the path where this instance is cached.

License

MIT — free to use and modify.

Metadata

Release files for pydantic-cacheable-model 2.0.1

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-cacheable-model 2.0.1
File Size Uploaded Provenance Actions
pydantic_cacheable_model-2.0.1.tar.gz 4.3 kB Without provenance Details for pydantic_cacheable_model-2.0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pydantic-cacheable-model 2.0.1
File Interpreter ABI Platform Actions
pydantic_cacheable_model-2.0.1-py3-none-any.whl Python 3 none any Details for pydantic_cacheable_model-2.0.1-py3-none-any.whl

Total release size: 10.0 kB

Release files / pydantic_cacheable_model-2.0.1.tar.gz

Download URL pydantic_cacheable_model-2.0.1.tar.gz
Size 4.3 kB
Tags Source
SHA-256 checksum
How to use checksums
2dbc16c9c5be142d84ba939694c534cc8caf447fda200028e6b4a244bed8603e
BLAKE2b-256 checksum
How to use checksums
4b087686b82dd6cd5992fdaa1d1be78ae6aa76f2646effd37ed0fbf407e177bb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.8.13

Release files / pydantic_cacheable_model-2.0.1-py3-none-any.whl

Download URL pydantic_cacheable_model-2.0.1-py3-none-any.whl
Size 5.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b0b4a505762c22d9620737c7dd34848830501fcdf72e507350dc0a9699805ca5
BLAKE2b-256 checksum
How to use checksums
a0cc8e0bd9846245c11e089b51082dfbd43604f152981f536409ef268fcca6c5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.8.13

Security for pydantic-cacheable-model 2.0.1

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.

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