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.11+


Usage

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

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

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

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

# Optionally handle missing caches or validation mismatches
maybe_user = UserModel.load(cache_id="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, CacheId

# 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: CacheId[str]
    joined: datetime


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

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


# 3) Custom identifier logic without using CacheId
class Document(CacheableModel):
    kind: str
    slug: str

    @property
    def cache_id(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_id).json for safe, stable filenames.
  • Data format: pretty-printed JSON. Enum values and datetime objects serialize automatically.
  • Choosing the identifier: mark one field with CacheId[T]. If you need custom logic, override the cache_id 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_id_to_filename(*, cache_id: str) -> str — classmethod; maps an id to a filename (default: SHA-256 hex + .json).
  • get_cache_path(*, cache_id: str) -> str — full path to the cache file for a given id.
  • load(*, cache_id: 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-1.0.1.tar.gz (4.2 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-1.0.1-py3-none-any.whl (5.6 kB view details)

Uploaded Python 3

File details

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

File metadata

File hashes

Hashes for pydantic_cacheable_model-1.0.1.tar.gz
Algorithm Hash digest
SHA256 e7d506a4359027751be7b2986a45f1575f3f8006d6465239aa4e0e88b8b9f012
MD5 d46f104fe349ae1e7053d05f7ed89981
BLAKE2b-256 b729996617ba158a1dfcaa52b2cc81f0c8ddb1615e84576de9fb3dbeed626cfe

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for pydantic_cacheable_model-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 476b8249c2b022baeedfc5adbc2b216695d734fd7171c2b6ddd583b28c7004a8
MD5 b0c44fdb7c0454c5d851f2a39a949dc8
BLAKE2b-256 9b1478618c38da004d3c3f70de1a35739d655c3bb83638f4f6aa51ad0ddd74f8

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