Skip to main content

Lightweight in-memory cache with TTL, LRU eviction, and tag-based invalidation

Project description

philiprehberger-cache-kit

Tests PyPI version Last updated

Lightweight in-memory cache with TTL, LRU eviction, and tag-based invalidation.

Installation

pip install philiprehberger-cache-kit

Usage

Basic Cache

from philiprehberger_cache_kit import Cache

cache: Cache[str] = Cache(max_size=1000)

cache.set("key", "value")
print(cache.get("key"))  # "value"

TTL (Time-to-Live)

cache = Cache(default_ttl=60.0)  # 60 seconds default

cache.set("session", "abc123")           # uses default TTL
cache.set("temp", "data", ttl=5.0)       # expires in 5 seconds
cache.set("permanent", "data", ttl=None) # no expiry when default is set

LRU Eviction

cache = Cache(max_size=100)

# When full, least recently used entries are evicted first
# Expired entries are evicted before non-expired ones
for i in range(200):
    cache.set(f"key-{i}", f"value-{i}")

print(cache.size)  # 100

Tag-Based Invalidation

cache.set("user:1", user_data, tags={"users", "team-a"})
cache.set("user:2", user_data, tags={"users", "team-b"})
cache.set("post:1", post_data, tags={"posts", "team-a"})

# Invalidate all entries tagged "team-a"
removed = cache.invalidate_by_tag("team-a")
print(removed)  # 2

Batch Operations

# Set multiple entries at once
cache.set_many({"a": 1, "b": 2, "c": 3}, ttl=30.0)

# Get multiple entries at once (skips missing/expired)
results = cache.get_many(["a", "b", "missing"])
print(results)  # {"a": 1, "b": 2}

Cache Statistics

from philiprehberger_cache_kit import Cache, CacheStats

cache: Cache[str] = Cache(max_size=100)

cache.set("x", "hello")
cache.get("x")        # hit
cache.get("missing")  # miss

stats = cache.stats()
print(stats.hits)      # 1
print(stats.misses)    # 1
print(stats.hit_rate)  # 0.5
print(stats.evictions) # 0
print(stats.expired)   # 0

cache.reset_stats()    # zero out all counters

Other Operations

cache.has("key")        # check existence
"key" in cache          # same as has()
cache.delete("key")     # delete single entry
cache.keys()            # list all non-expired keys
len(cache)              # count of non-expired entries
cache.get_entry("key")  # get CacheEntry with tags, expires_at
cache.clear()           # remove everything

API

Function / Class Description
Cache(max_size=1000, default_ttl=None) Create a new cache
.set(key, value, ttl=None, tags=None) Store a value
.get(key, default=None) Retrieve a value
.get_many(keys) Retrieve multiple values, skip missing/expired
.set_many(items, ttl=None) Store multiple values
.has(key) Check if key exists and is not expired
.delete(key) Remove a key
.invalidate_by_tag(tag) Remove all entries with a tag
.clear() Remove all entries
.keys() List non-expired keys
.get_entry(key) Get CacheEntry object (value, expires_at, tags)
.stats() Get CacheStats (hits, misses, evictions, expired, hit_rate)
.reset_stats() Zero out all stat counters
.size Number of stored entries
len(cache) Number of non-expired entries
key in cache Check key existence
CacheStats Dataclass with hits, misses, evictions, expired, hit_rate

Development

pip install -e .
python -m pytest tests/ -v

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT

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

philiprehberger_cache_kit-0.3.1.tar.gz (7.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

philiprehberger_cache_kit-0.3.1-py3-none-any.whl (5.5 kB view details)

Uploaded Python 3

File details

Details for the file philiprehberger_cache_kit-0.3.1.tar.gz.

File metadata

File hashes

Hashes for philiprehberger_cache_kit-0.3.1.tar.gz
Algorithm Hash digest
SHA256 42dec738398155ef262f39aac493ab1c94b882e7a6d975f2dfe0e0e208f7b87f
MD5 7b54eddb4af65bed715a058b9f1d2f1f
BLAKE2b-256 448ff9a4f65f25efcb429ff1e2426111557cf62ff1d2091ed7092291a458f177

See more details on using hashes here.

File details

Details for the file philiprehberger_cache_kit-0.3.1-py3-none-any.whl.

File metadata

File hashes

Hashes for philiprehberger_cache_kit-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 ad4b0d2e740e0b0289fddc863b6830c44f7a29324bb63c9392b59278d86e2b71
MD5 a545e106f47bc5f309a0f15a6b8f9ffa
BLAKE2b-256 9092509c01b30f42f915cdde140d89b7bac9d9bbb1acdbc0cbe8284a5bcb2043

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