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. Any storage that matches the protocol works the same way.

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

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.

get_registry from cachebind returns that index: get_registry(AsyncRedis).get("users").

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

Documentation

  • Leaderboard — ordered set of user ids, with users loaded from Postgres
  • Tag-Based Caching — bind key-value user cache and leaderboard entry under user:{id}, evict together on delete
  • Trie (Prefix Tree) — city names in a Redis Search trie, with cities loaded from Postgres on search
  • Write-Back Caching example — collect last-visit times, then save them to the database

Metadata

Release files for cachebind 1.0.2

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.0.2
File Size Uploaded Provenance Actions
cachebind-1.0.2.tar.gz 65.2 kB Without provenance Details for cachebind-1.0.2.tar.gz

Built distribution (wheel)

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

Total release size: 131.7 kB

Release files / cachebind-1.0.2.tar.gz

Download URL cachebind-1.0.2.tar.gz
Size 65.2 kB
Tags Source
SHA-256 checksum
How to use checksums
efe88645b74a8a08f36ddb4fd1c9e58951a479930b2a9175cab71d111ae027e8
BLAKE2b-256 checksum
How to use checksums
1473675182678b231f75635a048836c8f7f60d358954400b0cc278b5cd3561b9
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.0.2-py3-none-any.whl

Download URL cachebind-1.0.2-py3-none-any.whl
Size 66.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
665e2033626533b55957251373617eb67f7ee8a94ac7b1ca2df8e2b24a3a191d
BLAKE2b-256 checksum
How to use checksums
75f4cbf3cf00db500f54ec457206e461261162a1dbb2db3320b34f145c4e11ec
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.0.2

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