Skip to main content

Cachetta for Python

File-based caching for Python. Part of the Cachetta project, which provides the same caching API in Python and TypeScript -- learn it once, use it in either language.

Three doc layers: this README (overview), the docs/ folder bundled with this package, and the hosted docs site. Each ## below mirrors a section in docs/python.md.

Requires Python 3.12+.

Install

uv add cachetta

Basic Usage

from datetime import timedelta
from cachetta import Cachetta, read_cache, write_cache

cache = Cachetta(path='./cache.json', duration=timedelta(days=1))

with read_cache(cache) as data:
    if data is None:
        data = fetch_data()
        write_cache(cache, data)

→ Basic Usage

Decorators

@Cachetta(path='/my-cache.json')
def get_data():
    return compute_expensive_value()

→ Decorators

Async Support

@Cachetta(path='./async-cache.json')
async def get_async_data():
    return await fetch_data()

I/O for decorated async functions runs via asyncio.to_thread(). Explicit primitives are async_read_cache / async_write_cache.

→ Async Support

Function Wrapper

cache = Cachetta(path='./my-cache.json')
cached_get_data = cache(get_data)
result = cached_get_data()

→ Function Wrapper

Per-Argument Cache Files

Pass a callable path to vary the cache file by argument. A str/Path path is used verbatim regardless of arguments.

→ Per-Argument Cache Files

Conditional Caching

cache = Cachetta(path='./cache.json', condition=lambda r: r is not None)

→ Conditional Caching

Stale-While-Revalidate

cache = Cachetta(
    path='./cache.json',
    duration=timedelta(hours=1),
    stale_duration=timedelta(minutes=30),
)

→ Stale-While-Revalidate

Cache Invalidation

cache.invalidate()       # or cache.clear()
await cache.ainvalidate()

→ Cache Invalidation

Cache Inspection

cache.exists()  # bool
cache.age()     # timedelta | None
cache.info()    # dict

Async variants: aexists, aage, ainfo.

→ Cache Inspection

Path Operator

cache = Cachetta(path='./cache')
with read_cache(cache / 'my-data.json') as data:
    ...

# Subfolder for auto-hashed entries
sub = cache / 'llm-calls'

# Callable for custom layouts (resolved at call time)
custom = cache / (lambda kind, ident: f'{kind}/{ident}.pkl')

→ Path Operator

Dynamic Cache Paths

@Cachetta(path=lambda n: f"./cache/{n}.json")
def foo(n: int):
    ...

→ Dynamic Cache Paths

Specifying Paths

new_cache = cache.copy(read=False, duration=timedelta(days=2))

→ Specifying Paths

Method Decorators

Methods work as-is; the receiver (self/cls) is not part of the cache key.

class DataService:
    @Cachetta(path=lambda user_id: f'./cache/{user_id}.json')
    def get_data(self, user_id):
        ...

→ Method Decorators

Pickle Security

A restricted unpickler blocks arbitrary code execution from tampered cache files. Add custom types to allowed_pickle_types to whitelist them.

cache = Cachetta(path='./cache.dat', allowed_pickle_types={UserProfile})

→ Pickle Security

Error Handling

read_cache yields None for missing or corrupt files.

→ Error Handling

Logging

import logging
logging.getLogger("cachetta").setLevel(logging.DEBUG)

→ Logging

Configuration Reference

Option Type Default
path str | Callable required
read / write bool True
duration timedelta 7 days
condition Callable None
stale_duration timedelta None
allowed_pickle_types set[type] None

→ Configuration Reference

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cachetta-0.6.12.tar.gz (24.4 kB view details)

Uploaded Source

File details

Details for the file cachetta-0.6.12.tar.gz.

File metadata

  • Download URL: cachetta-0.6.12.tar.gz
  • Upload date:
  • Size: 24.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for cachetta-0.6.12.tar.gz
Algorithm Hash digest
SHA256 b440be45d6bff36d50016ad5fd6be4094cc1fe9bb7a3f046e953e020009ec544
MD5 28c7b828281f321a74872ec5bb598830
BLAKE2b-256 88ca2d33692db659d86196299cdfdb3af3711c76569478c900e237dc6bda249c

See more details on using hashes here.

Provenance

The following attestation bundles were made for cachetta-0.6.12.tar.gz:

Publisher: release.yaml on thekevinscott/cachetta

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

0.7.0

1 file

0.6.15

1 file

0.6.14

1 file

0.6.13

1 file

This release

0.6.12 This release

1 file

0.6.11

1 file

0.6.10

1 file

0.6.9

1 file

0.6.8

1 file

0.6.7

1 file

0.6.6

1 file

0.6.5

1 file

0.6.4

1 file

0.6.3

1 file

0.6.0

2 files

0.5.0

2 files

0.1.0

2 files

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