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 trailingModeland converting CamelCase to kebab-case (e.g.,UserModel→user,LongNameModel→long-name). - File naming:
sha256(cache_key).jsonfor safe, stable filenames. - Data format: pretty-printed JSON.
Enumvalues anddatetimeobjects serialize automatically. - Choosing the key: mark one field with
CacheKey[T]. If you need custom logic, override thecache_keyproperty instead.
API
CACHE_ROOT: str— class var; default".cache".CACHE_DIRNAME: str | None— class var; override to force subdirectory name. IfNone, 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. Ifnot_found_ok=True, returnsNoneon missing or, when validation fails, returnsNoneand 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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pydantic_cacheable_model-2.0.1.tar.gz.
File metadata
- Download URL: pydantic_cacheable_model-2.0.1.tar.gz
- Upload date:
- Size: 4.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.8.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2dbc16c9c5be142d84ba939694c534cc8caf447fda200028e6b4a244bed8603e
|
|
| MD5 |
ba51bebf5c41e9f8b10dec59cd8be778
|
|
| BLAKE2b-256 |
4b087686b82dd6cd5992fdaa1d1be78ae6aa76f2646effd37ed0fbf407e177bb
|
File details
Details for the file pydantic_cacheable_model-2.0.1-py3-none-any.whl.
File metadata
- Download URL: pydantic_cacheable_model-2.0.1-py3-none-any.whl
- Upload date:
- Size: 5.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.8.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b0b4a505762c22d9620737c7dd34848830501fcdf72e507350dc0a9699805ca5
|
|
| MD5 |
97194c7fa0ae86887a61a486ee7b3b98
|
|
| BLAKE2b-256 |
a0cc8e0bd9846245c11e089b51082dfbd43604f152981f536409ef268fcca6c5
|