Skip to main content

cachebind

A Python library that names a cache binding — one storage key, a serializer, and a storage — and reads or writes Python values through it.

What is it for? Cachebind is a way to name a cache binding and use it from application code. An index holds one storage key, a serializer, and a storage. You build it once. Each call takes your storage client and reads or writes a Python value through that binding. Redis storages are included. A custom storage works the same way when it subclasses the storage interface.

What can an index store? A key-value index stores one model per id. A set index stores members in one set. An ordered set index stores members with scores, lowest score first. A trie index stores suggestion strings with scores and keeps each member as the payload. search returns those members in rank order. Each has a sync builder and an async builder.

Indexes

Build an index once with build_async_key_value_index, build_async_set_index, build_async_ordered_set_index, or build_async_trie_index. Each builder registers the index for AsyncRedis (async) or Redis (sync). Pass a key, the value type, a serializer instance, and a storage instance. Optionally pass breadcrumbs (default ColonBreadcrumbs) on key-value, set, and ordered-set builders. Trie indexes always use NoopBreadcrumbs and do not accept breadcrumbs. Then pass a storage client into every call.

set and add return one breadcrumb. mset and madd return one breadcrumb per item. By default, breadcrumbs encode the index key and eviction identifier. With NoopBreadcrumbs, writes return an empty breadcrumb. Decode a breadcrumb to get the index name and identifier, then call evict(client, identifier) on that index (not supported on trie indexes).

A tag keeper groups those breadcrumbs in Redis sets. Create SetTagKeeper(storage=RedisSetStorage()) or AsyncSetTagKeeper with async set storage; optional name defaults to "default", optional breadcrumbs defaults to ColonBreadcrumbs() for decoding on evict. Tag keepers use the same Redis / AsyncRedis registry as build_*. Each logical tag is one set at tag_keeper:{name}:{tag}. After writes, call add(client, tag, breadcrumb) or madd(client, tag, breadcrumbs); call evict(client, tag) to decode every breadcrumb in that set, evict through the index registry, and delete the set.

A lock keeper holds named locks in key-value storage. Create KeyValueLockKeeper(storage=RedisHashStorage()) or AsyncKeyValueLockKeeper with async hash storage; optional name defaults to "default". Each lock is one field of the hash lock_keeper:{name}. lock yields whether this caller acquired it and releases that token when the block exits.

from uuid import UUID

from pydantic import BaseModel
from redis.asyncio import Redis as AsyncRedis

from cachebind import build_async_key_value_index
from cachebind.serializers.pydantic_serializer import PydanticSerializer
from cachebind.storage import AsyncRedisHashStorage

class User(BaseModel):
    id: UUID
    name: str

ada = User(id=UUID("12345678-1234-5678-1234-567812345678"), name="Ada")

users = build_async_key_value_index(
    "users",
    id_type=UUID,
    model_type=User,
    serializer=PydanticSerializer(User),
    storage=AsyncRedisHashStorage(),
)

async def main() -> None:
    client = AsyncRedis(decode_responses=True)
    await users.set(client, ada.id, ada, ttl=60)
    value = await users.get(client, ada.id)
    await users.delete(client, ada.id)

ttl is a whole number of seconds on set and mset. Omit it, or pass None, and the write does not expire. mset applies that one TTL to every id. delete removes one id. mdelete removes every given id. A missing id is not an error.

Inside main, the same client works for a set index.

from cachebind import IntSerializer, build_async_set_index
from cachebind.storage import AsyncRedisSetStorage

active = build_async_set_index(
    "active_users",
    member_type=int,
    serializer=IntSerializer(),
    storage=AsyncRedisSetStorage(),
)

    await active.add(client, 1)
    present = await active.contains(client, 1)
    await active.remove(client, 1)

remove drops one member. A missing member is not an error. Sets have no TTL.

An ordered set uses the same client. Each member has one score. Adding a member that is already present updates its score. rank is 0-based, from the lowest score. range includes both ends. Ordered sets have no TTL.

from cachebind import IntSerializer, build_async_ordered_set_index
from cachebind.storage import AsyncRedisOrderedSetStorage

ranking = build_async_ordered_set_index(
    "user_scores",
    member_type=int,
    serializer=IntSerializer(),
    storage=AsyncRedisOrderedSetStorage(),
)

    await ranking.add(client, 1, 10.0)
    place = await ranking.rank(client, 1)
    top = await ranking.range(client, 0, 0)
    await ranking.remove(client, 1)

A trie uses the same client. The suggestion string is the text you complete. The member is stored as the payload. search deserializes those payloads in rank order. limit defaults to 10. A trie has no TTL.

from cachebind import IntSerializer, build_async_trie_index
from cachebind.storage import AsyncRedisTrieStorage

cities = build_async_trie_index(
    "cities",
    member_type=int,
    serializer=IntSerializer(),
    storage=AsyncRedisTrieStorage(),
)

    await cities.add(client, "Paris", 1, 900.0)
    matches = await cities.search(client, "P")
    await cities.remove(client, "Paris")

matches is [1]. Redis 8 includes the suggestion commands this storage sends.

Sync indexes use build_key_value_index, build_set_index, build_ordered_set_index, and build_trie_index with the matching sync storage. Those calls are not awaited.

Each build_* registers the index under its key for Redis or AsyncRedis. get_registry(AsyncRedis).get("users") returns it; for other client types, construct an index and call register_index(client_type, name, index).

Install

pip install cachebind
pip install "cachebind[redis]"
pip install "cachebind[pydantic]"
pip install "cachebind[redis,pydantic]"

From a checkout, the same extras are:

pip install -e ".[dev]"
pip install -e ".[redis]"
pip install -e ".[redis,pydantic]"

Runtime dependencies live in pyproject.toml under [project] dependencies. Optional Redis and Pydantic support, and the test tools, live in extras. A plain install does not pull Redis or Pydantic. There is no requirements.txt.

Test

pytest

Recipes

Metadata

Release files for cachebind 1.6.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cachebind 1.6.0
File Size Uploaded Provenance Actions
cachebind-1.6.0.tar.gz 87.1 kB Without provenance Details for cachebind-1.6.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cachebind 1.6.0
File Interpreter ABI Platform Actions
cachebind-1.6.0-py3-none-any.whl Python 3 none any Details for cachebind-1.6.0-py3-none-any.whl

Total release size: 180.0 kB

Release files / cachebind-1.6.0.tar.gz

Download URL cachebind-1.6.0.tar.gz
Size 87.1 kB
Tags Source
SHA-256 checksum
How to use checksums
dce003dedcdceecc14311b5a6ccad1e510f4faa82a9a695eb4f5c40d3d9715ae
BLAKE2b-256 checksum
How to use checksums
e7563ca6733a9765b3066e1d800c1ac1f11f39649508fa4266c5b5ae9b332cee
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.15.2

Release files / cachebind-1.6.0-py3-none-any.whl

Download URL cachebind-1.6.0-py3-none-any.whl
Size 92.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2c6b25a71eb89e96d0c147d5dc1c72ca61a98fb9fc497b23c09e051f5646de5f
BLAKE2b-256 checksum
How to use checksums
52fc2dbc945555b5c0a4741bcda2a960d482cf18bca5d87adc6acea726f59bfe
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.15.2

Security for cachebind 1.6.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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