Theine Cache
raw JSON → 2.1.0 verified Mon Apr 27 auth: no python
Theine is a high-performance, in-memory cache library for Python with support for TTL, LRU, LFU, and windowed TinyLFU eviction policies. Current version 2.1.0 requires Python >=3.10 and is actively maintained.
pip install theine-core Common errors
error ModuleNotFoundError: No module named 'theine' ↓
cause Installed the package 'theine-core' but tried to import 'theine_core' or misspelled the import.
fix
Run: pip install theine-core
Then import: from theine import Cache
error TypeError: __init__() got an unexpected keyword argument 'max_size' ↓
cause In version 2.x, the parameter was renamed from 'max_size' to 'maxsize'.
fix
Use 'maxsize' instead of 'max_size'. Example: Cache('lru', maxsize=100)
Warnings
gotcha The package name is 'theine-core' on PyPI, but the import module is 'theine'. Many users mistakenly import from 'theine_core' or 'theine.core'. ↓
fix Use 'from theine import Cache' (not theine-core, not theine_core).
breaking In version 2.x, the API changed: The Cache class no longer accepts 'policy' as a string like 'lru' directly? Verify: Actually it does. But the 'maxsize' parameter was renamed from 'max_size' in v1.x. ↓
fix Use 'maxsize' instead of 'max_size'. Also, the 'ttl' parameter now expects seconds as an integer, not a timedelta.
gotcha Theine's thread-safety is limited: concurrent writes from multiple threads may cause race conditions. The documentation notes that Cache is not thread-safe for writes. ↓
fix Use external locking if you need concurrent writes, or consider a thread-safe cache like cachetools.
gotcha When using 'tinylfu' policy, the 'maxsize' must be a power of two for optimal performance; otherwise it may degrade. ↓
fix Set maxsize to a power of two (e.g., 1024, 2048) when using 'tinylfu' or 'windowed_tinylfu'.
Imports
- Cache wrong
from theine_core import Cachecorrectfrom theine import Cache - TieredCache
from theine import TieredCache
Quickstart
from theine import Cache
cache = Cache("lru", maxsize=100, ttl=60)
cache.set("key", "value")
print(cache.get("key")) # 'value'
# Context manager
with Cache("tinylfu", maxsize=1000) as c:
c.set("a", 1)
print(c.get("a")) # 1