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.0.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.0-py3-none-any.whl (5.7 kB view details)

Uploaded Python 3

File details

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

File metadata

File hashes

Hashes for pydantic_cacheable_model-2.0.0.tar.gz
Algorithm Hash digest
SHA256 4696927afc5606fd4f7c3e685c73172f82ac4b6dd6b1e55ba3b9c05a69f705b9
MD5 38ce365798fbdc26ce4dda1c8e1f2e9a
BLAKE2b-256 87802302f7e3560288bc53a6a4bed729bedb40ff741cfd39c0872077430da26c

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for pydantic_cacheable_model-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 d3578a720db1093ae25ba201f9e842664baa7db6ca004dc7b1e8458767c22a77
MD5 7540882de992e4bf986e0a3cdfbbd5ce
BLAKE2b-256 631a3e56c4235aa14436bdae426f6d5e83bc2fac42185be723f1da24e7708712

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