Skip to main content

Small Pydantic helpers for cacheable models

Project description

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., UserModeluser, LongNameModellong-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.

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_cacheable_model-2.0.1.tar.gz (4.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pydantic_cacheable_model-2.0.1-py3-none-any.whl (5.7 kB view details)

Uploaded Python 3

File details

Details for the file pydantic_cacheable_model-2.0.1.tar.gz.

File metadata

File hashes

Hashes for pydantic_cacheable_model-2.0.1.tar.gz
Algorithm Hash digest
SHA256 2dbc16c9c5be142d84ba939694c534cc8caf447fda200028e6b4a244bed8603e
MD5 ba51bebf5c41e9f8b10dec59cd8be778
BLAKE2b-256 4b087686b82dd6cd5992fdaa1d1be78ae6aa76f2646effd37ed0fbf407e177bb

See more details on using hashes here.

File details

Details for the file pydantic_cacheable_model-2.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for pydantic_cacheable_model-2.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 b0b4a505762c22d9620737c7dd34848830501fcdf72e507350dc0a9699805ca5
MD5 97194c7fa0ae86887a61a486ee7b3b98
BLAKE2b-256 a0cc8e0bd9846245c11e089b51082dfbd43604f152981f536409ef268fcca6c5

See more details on using hashes here.

Supported by

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