Spaces:
Paused
Paused
File size: 30,890 Bytes
1293e20 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 | # /// zerodep
# version = "0.2.4"
# deps = []
# tier = "subsystem"
# category = "storage"
# note = "Install/update via `zerodep add cache`"
# ///
"""Zero-dependency caching with TTL, eviction policies, and async support.
stdlib only, Python 3.10+.
Part of zerodep: https://github.com/Oaklight/zerodep
Copyright (c) 2026 Peng Ding. MIT License.
Provides: LRUCache, FIFOCache, LFUCache, TTLCache cache classes (MutableMapping),
``cached`` decorator with sync/async auto-detection, and convenience decorators
``lru_cache``, ``ttl_cache``, ``lfu_cache``, ``fifo_cache``.
Does NOT implement: TLRUCache (per-item TTL function), MRUCache, RRCache,
``cachedmethod``, ``condition`` parameter, multiple backends, serialization.
Example::
from cache import lru_cache, ttl_cache, LRUCache, cached
# Convenience decorator (like functools.lru_cache but with more policies)
@lru_cache(maxsize=256)
def fibonacci(n):
return n if n < 2 else fibonacci(n - 1) + fibonacci(n - 2)
# TTL decorator
@ttl_cache(maxsize=100, ttl=60)
def fetch_config(key):
return load_from_db(key)
# Async support (auto-detected)
@lru_cache(maxsize=128)
async def fetch_data(url):
return await async_get(url)
# Direct cache class usage
cache = LRUCache(maxsize=1024)
cache["key"] = "value"
# Advanced: cached() with explicit lock
import threading
@cached(LRUCache(128), lock=threading.Lock(), info=True)
def thread_safe_compute(x):
return expensive(x)
"""
from __future__ import annotations
import collections
import collections.abc
import functools
import inspect
import time
from typing import Any, Callable
# ββ Key Functions ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class _HashedTuple(tuple):
"""Tuple subclass that caches its hash value for fast repeated lookups."""
__hashvalue: int | None = None
def __hash__(self, hash=tuple.__hash__): # type: ignore[override]
hashvalue = self.__hashvalue
if hashvalue is None:
self.__hashvalue = hashvalue = hash(self)
return hashvalue
def __add__(self, other, add=tuple.__add__):
return _HashedTuple(add(self, other))
def __radd__(self, other, add=tuple.__add__):
return _HashedTuple(add(other, self))
_KWMARK = (_HashedTuple,)
def hashkey(*args: Any, **kwargs: Any) -> _HashedTuple:
"""Return a cache key for the given positional and keyword arguments.
This is the default key function for all cache decorators.
"""
if kwargs:
return _HashedTuple(args + _KWMARK + tuple(sorted(kwargs.items())))
return _HashedTuple(args)
def methodkey(_self: Any, *args: Any, **kwargs: Any) -> _HashedTuple:
"""Like ``hashkey`` but ignores the first positional argument (``self``).
Use as the key function when caching instance methods.
"""
return hashkey(*args, **kwargs)
def typedkey(*args: Any, **kwargs: Any) -> _HashedTuple:
"""Like ``hashkey`` but includes type information, so ``f(3)`` and
``f(3.0)`` are cached separately.
"""
if kwargs:
sorted_items = tuple(sorted(kwargs.items()))
return _HashedTuple(
args
+ _KWMARK
+ sorted_items
+ tuple(type(v) for v in args)
+ tuple(type(v) for _, v in sorted_items)
)
return _HashedTuple(args + tuple(type(v) for v in args))
# ββ Cache Info βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CacheInfo = collections.namedtuple(
"CacheInfo", ["hits", "misses", "maxsize", "currsize"]
)
# ββ Cache Base Class βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class _DefaultSize:
"""Lightweight size tracker that always returns 1 for any key."""
__slots__ = ()
def __getitem__(self, _: Any) -> int:
return 1
def __setitem__(self, _: Any, __: Any) -> None:
pass
def pop(self, _: Any, *args: Any) -> int:
return 1
def clear(self) -> None:
pass
class Cache(collections.abc.MutableMapping):
"""Mutable mapping to serve as a simple cache or cache base class.
Subclasses must override ``popitem`` to implement a specific eviction
policy. The base class evicts arbitrary items (dict order).
Args:
maxsize: Maximum capacity (item count or weighted size).
getsizeof: Optional callable returning the size of a value.
Defaults to 1 per item.
"""
__marker = object()
def __init__(
self,
maxsize: int | float,
getsizeof: Callable[[Any], int] | None = None,
):
if maxsize < 0:
raise ValueError("maxsize must be non-negative")
self.__data: dict[Any, Any] = {}
self.__currsize: int | float = 0
self.__maxsize = maxsize
if getsizeof is not None:
self.__size: dict | _DefaultSize = {}
self.getsizeof = getsizeof # type: ignore[assignment]
else:
self.__size = _DefaultSize()
def __repr__(self) -> str:
cls = self.__class__.__name__
return (
f"{cls}({self.__data!r}, "
f"maxsize={self.__maxsize}, currsize={self.__currsize})"
)
def __getitem__(self, key: Any) -> Any:
try:
return self.__data[key]
except KeyError:
return self.__missing__(key)
def __setitem__(self, key: Any, value: Any) -> None:
maxsize = self.__maxsize
size = self.getsizeof(value)
if size > maxsize:
raise ValueError("value too large")
if key in self.__data:
diffsize = size - self.__size[key]
else:
diffsize = size
while self.__currsize + diffsize > maxsize:
self.popitem()
if key in self.__data:
# Key might have been evicted during popitem loop
self.__currsize -= self.__size[key]
self.__data[key] = value
self.__size[key] = size
self.__currsize += size
def __delitem__(self, key: Any) -> None:
size = self.__size.pop(key)
del self.__data[key]
self.__currsize -= size
def __contains__(self, key: object) -> bool:
return key in self.__data
def __missing__(self, key: Any) -> Any:
raise KeyError(key)
def __iter__(self):
return iter(self.__data)
def __len__(self) -> int:
return len(self.__data)
@staticmethod
def getsizeof(value: Any) -> int:
"""Return the size of *value*. Defaults to 1."""
return 1
@property
def maxsize(self) -> int | float:
"""Maximum cache capacity."""
return self.__maxsize
@property
def currsize(self) -> int | float:
"""Current cache size (sum of item sizes)."""
return self.__currsize
def get(self, key: Any, default: Any = None) -> Any:
if key in self:
return self[key]
return default
def pop(self, key: Any, default: Any = __marker) -> Any:
if key in self:
value = self[key]
del self[key]
return value
if default is self.__marker:
raise KeyError(key)
return default
def setdefault(self, key: Any, default: Any = None) -> Any:
if key in self:
return self[key]
try:
self[key] = default
except ValueError:
pass
return default
def popitem(self) -> tuple[Any, Any]:
"""Remove and return an arbitrary ``(key, value)`` pair.
Subclasses override this to implement eviction policies.
"""
try:
key = next(iter(self.__data))
except StopIteration:
raise KeyError(f"{type(self).__name__} is empty") from None
return key, self.pop(key)
def clear(self) -> None:
self.__data.clear()
self.__size.clear()
self.__currsize = 0
# ββ FIFO Cache βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class FIFOCache(Cache):
"""First In First Out (FIFO) cache implementation.
Evicts the oldest inserted item when the cache is full. Accessing an
item does **not** change its eviction priority.
"""
def __init__(
self,
maxsize: int | float,
getsizeof: Callable[[Any], int] | None = None,
):
super().__init__(maxsize, getsizeof)
self.__order: collections.OrderedDict[Any, None] = collections.OrderedDict()
def __setitem__(self, key: Any, value: Any) -> None:
if key in self:
del self.__order[key]
super().__setitem__(key, value)
self.__order[key] = None
def __delitem__(self, key: Any) -> None:
super().__delitem__(key)
del self.__order[key]
def popitem(self) -> tuple[Any, Any]:
"""Remove and return the oldest inserted ``(key, value)`` pair."""
try:
key = next(iter(self.__order))
except StopIteration:
raise KeyError(f"{type(self).__name__} is empty") from None
return key, self.pop(key)
def clear(self) -> None:
super().clear()
self.__order.clear()
# ββ LRU Cache ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class LRUCache(Cache):
"""Least Recently Used (LRU) cache implementation.
Evicts the least recently accessed item when the cache is full.
Both reads and writes count as accesses.
"""
def __init__(
self,
maxsize: int | float,
getsizeof: Callable[[Any], int] | None = None,
):
super().__init__(maxsize, getsizeof)
self.__order: collections.OrderedDict[Any, None] = collections.OrderedDict()
def __getitem__(self, key: Any) -> Any:
# Bypass super().__getitem__ to avoid MRO dispatch overhead;
# call Cache.__getitem__ directly + inline move_to_end.
value = Cache.__getitem__(self, key)
self.__order.move_to_end(key)
return value
def __setitem__(self, key: Any, value: Any) -> None:
Cache.__setitem__(self, key, value)
try:
self.__order.move_to_end(key)
except KeyError:
self.__order[key] = None
def __delitem__(self, key: Any) -> None:
Cache.__delitem__(self, key)
del self.__order[key]
def popitem(self) -> tuple[Any, Any]:
"""Remove and return the least recently used ``(key, value)`` pair."""
try:
key = next(iter(self.__order))
except StopIteration:
raise KeyError(f"{type(self).__name__} is empty") from None
return key, self.pop(key)
def clear(self) -> None:
Cache.clear(self)
self.__order.clear()
# ββ LFU Cache ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class _LFUNode:
"""Doubly-linked node for the LFU frequency list."""
__slots__ = ("count", "keys", "prev", "next")
def __init__(self, count: int = 0):
self.count = count
self.keys: set[Any] = set()
self.prev: _LFUNode = self
self.next: _LFUNode = self
def insert_after(self, node: _LFUNode) -> None:
"""Insert *node* after this node."""
node.prev = self
node.next = self.next
self.next.prev = node
self.next = node
def unlink(self) -> None:
"""Remove this node from the linked list."""
self.prev.next = self.next
self.next.prev = self.prev
class LFUCache(Cache):
"""Least Frequently Used (LFU) cache implementation.
Evicts the least frequently accessed item when the cache is full.
All operations are O(1).
"""
def __init__(
self,
maxsize: int | float,
getsizeof: Callable[[Any], int] | None = None,
):
super().__init__(maxsize, getsizeof)
self.__root = _LFUNode() # sentinel
self.__links: dict[Any, _LFUNode] = {}
def __getitem__(self, key: Any) -> Any:
value = super().__getitem__(key)
self.__touch(key)
return value
def __setitem__(self, key: Any, value: Any) -> None:
existed = key in self
super().__setitem__(key, value)
if existed:
self.__touch(key)
else:
# New key starts at count=1
root = self.__root
first = root.next
if first is root or first.count != 1:
node = _LFUNode(count=1)
root.insert_after(node)
else:
node = first
node.keys.add(key)
self.__links[key] = node
def __delitem__(self, key: Any) -> None:
super().__delitem__(key)
node = self.__links.pop(key)
node.keys.discard(key)
if not node.keys:
node.unlink()
def __touch(self, key: Any) -> None:
"""Increment frequency count for *key*."""
node = self.__links[key]
new_count = node.count + 1
nxt = node.next
if nxt is self.__root or nxt.count != new_count:
new_node = _LFUNode(count=new_count)
node.insert_after(new_node)
else:
new_node = nxt
new_node.keys.add(key)
node.keys.discard(key)
self.__links[key] = new_node
if not node.keys:
node.unlink()
def popitem(self) -> tuple[Any, Any]:
"""Remove and return the least frequently used ``(key, value)`` pair."""
root = self.__root
node = root.next
if node is root:
raise KeyError(f"{type(self).__name__} is empty")
key = next(iter(node.keys))
# Bypass self.pop β self[key] β __touch to avoid wasteful
# frequency increment on a key that is about to be deleted.
value = Cache.__getitem__(self, key)
del self[key]
return key, value
def clear(self) -> None:
super().clear()
self.__links.clear()
self.__root.prev = self.__root
self.__root.next = self.__root
# ββ TTL Cache ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class _Timer:
"""Wraps a timer function with nestable time-freezing.
Used by TTLCache to ensure time consistency within a single operation.
"""
__slots__ = ("_timer", "_nesting", "_time")
def __init__(self, timer: Callable[[], float] = time.monotonic):
self._timer = timer
self._nesting = 0
self._time: float = 0.0
def __call__(self) -> float:
if self._nesting == 0:
return self._timer()
return self._time
def __enter__(self) -> float:
if self._nesting == 0:
self._time = self._timer()
self._nesting += 1
return self._time
def __exit__(self, *exc: Any) -> None:
self._nesting -= 1
class _TTLLink:
"""Doubly-linked node for TTLCache expiry ordering."""
__slots__ = ("key", "expires", "prev", "next")
def __init__(
self,
key: Any = None,
expires: float = 0.0,
):
self.key = key
self.expires = expires
self.prev: _TTLLink = self
self.next: _TTLLink = self
def unlink(self) -> None:
self.prev.next = self.next
self.next.prev = self.prev
class TTLCache(LRUCache):
"""LRU cache with per-item time-to-live (TTL).
Items are evicted when they expire (checked lazily on access) or when
the cache is full (LRU order).
Args:
maxsize: Maximum cache capacity.
ttl: Time-to-live in seconds for each item.
timer: Callable returning the current time (default: ``time.monotonic``).
getsizeof: Optional callable returning the size of a value.
"""
def __init__(
self,
maxsize: int | float,
ttl: float,
*,
timer: Callable[[], float] = time.monotonic,
getsizeof: Callable[[Any], int] | None = None,
):
LRUCache.__init__(self, maxsize, getsizeof)
self.__ttl = ttl
self.__timer = _Timer(timer)
self.__root = _TTLLink() # sentinel for expiry list
self.__links: dict[Any, _TTLLink] = {}
@property
def ttl(self) -> float:
"""Time-to-live in seconds."""
return self.__ttl
@property
def timer(self) -> _Timer:
"""The timer function."""
return self.__timer
def __contains__(self, key: object) -> bool:
link = self.__links.get(key)
if link is None:
return False
return self.__timer() < link.expires
def __getitem__(self, key: Any) -> Any:
link = self.__links.get(key)
if link is not None and self.__timer() >= link.expires:
del self[key]
return self.__missing__(key)
# Bypass LRUCache.__getitem__ β Cache.__getitem__ call chain;
# inline both to save one method-call and one dict lookup.
# Same direct-call pattern used by LFUCache.popitem.
value = Cache.__getitem__(self, key)
self._LRUCache__order.move_to_end(key) # type: ignore[attr-defined]
return value
def __setitem__(self, key: Any, value: Any) -> None:
with self.__timer as now:
self.expire(now)
LRUCache.__setitem__(self, key, value)
# Update or create expiry link
link = self.__links.get(key)
if link is not None:
link.unlink()
else:
link = _TTLLink()
self.__links[key] = link
link.key = key
link.expires = now + self.__ttl
# Append to end of expiry list (newest)
tail = self.__root.prev
link.prev = tail
link.next = self.__root
tail.next = link
self.__root.prev = link
def __delitem__(self, key: Any) -> None:
LRUCache.__delitem__(self, key)
link = self.__links.pop(key)
link.unlink()
def __iter__(self):
now = self.__timer()
for key in super().__iter__():
link = self.__links.get(key)
if link is not None and now < link.expires:
yield key
def __len__(self) -> int:
now = self.__timer()
# Single dict lookup via .get() instead of ``key in`` + ``[key]``.
links_get = self.__links.get
return sum(
1
for key in super().__iter__()
if (link := links_get(key)) is not None and now < link.expires
)
@property
def currsize(self) -> int | float:
"""Current size, excluding expired items."""
self.expire()
return super().currsize
def expire(self, time: float | None = None) -> list[tuple[Any, Any]]:
"""Remove expired items and return them as a list of ``(key, value)`` pairs."""
if time is None:
time = self.__timer()
root = self.__root
expired: list[tuple[Any, Any]] = []
link = root.next
while link is not root and link.expires <= time:
nxt = link.next
key = link.key
try:
value = Cache.__getitem__(self, key)
expired.append((key, value))
del self[key]
except KeyError:
pass
link = nxt
return expired
def clear(self) -> None:
LRUCache.clear(self)
self.__links.clear()
self.__root.prev = self.__root
self.__root.next = self.__root
# ββ Decorators βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_MISS = object() # sentinel for cache lookup miss
class _Stats:
"""Mutable hit/miss counters shared by cache wrapper closures."""
__slots__ = ("hits", "misses")
def __init__(self) -> None:
self.hits = 0
self.misses = 0
def _get_cache_maxsize(
cache: collections.abc.MutableMapping,
) -> int | float | None:
"""Return maxsize if *cache* is a ``Cache`` instance, else ``None``."""
return cache.maxsize if isinstance(cache, Cache) else None
def _get_cache_currsize(cache: collections.abc.MutableMapping) -> int | float:
"""Return current size of *cache*."""
return cache.currsize if isinstance(cache, Cache) else len(cache)
def _attach_cache_info(
wrapper: Callable,
cache: collections.abc.MutableMapping,
lock: Any | None,
stats: _Stats,
maxsize: int | float | None,
) -> None:
"""Attach ``cache_info()`` and ``cache_clear()`` methods to *wrapper*."""
def cache_info() -> CacheInfo:
return CacheInfo(stats.hits, stats.misses, maxsize, _get_cache_currsize(cache))
def cache_clear() -> None:
with lock if lock else _no_lock():
cache.clear()
stats.hits = stats.misses = 0
wrapper.cache_info = cache_info # type: ignore[attr-defined]
wrapper.cache_clear = cache_clear # type: ignore[attr-defined]
def _attach_noop_info(
wrapper: Callable,
stats: _Stats,
) -> None:
"""Attach ``cache_info()`` and ``cache_clear()`` for a no-op wrapper."""
def cache_info() -> CacheInfo:
return CacheInfo(stats.hits, stats.misses, None, 0)
def cache_clear() -> None:
stats.hits = stats.misses = 0
wrapper.cache_info = cache_info # type: ignore[attr-defined]
wrapper.cache_clear = cache_clear # type: ignore[attr-defined]
def _make_sync_wrapper(
fn: Callable,
cache: collections.abc.MutableMapping | None,
key: Callable,
lock: Any | None,
info: bool,
) -> Callable:
"""Build a synchronous caching wrapper."""
stats = _Stats()
if cache is None:
def wrapper(*args: Any, **kwargs: Any) -> Any:
stats.misses += 1
return fn(*args, **kwargs)
if info:
_attach_noop_info(wrapper, stats)
return wrapper
# Pre-cache method references to avoid attribute lookup per call.
cache_getitem = cache.__getitem__
cache_setitem = cache.__setitem__
cache_setdefault = cache.setdefault
if lock is not None:
def wrapper(*args: Any, **kwargs: Any) -> Any:
k = key(*args, **kwargs)
with lock:
try:
result = cache_getitem(k)
except KeyError:
result = _MISS
if result is not _MISS:
stats.hits += 1
return result
stats.misses += 1
v = fn(*args, **kwargs)
# Inline thread-safe store (was _cache_store_default).
with lock:
try:
return cache_setdefault(k, v)
except ValueError:
return v
else:
def wrapper(*args: Any, **kwargs: Any) -> Any:
k = key(*args, **kwargs)
try:
result = cache_getitem(k)
except KeyError:
stats.misses += 1
v = fn(*args, **kwargs)
try:
cache_setitem(k, v)
except ValueError:
pass
return v
stats.hits += 1
return result
if info:
_attach_cache_info(wrapper, cache, lock, stats, _get_cache_maxsize(cache))
return wrapper
def _make_async_wrapper(
fn: Callable,
cache: collections.abc.MutableMapping | None,
key: Callable,
lock: Any | None,
info: bool,
) -> Callable:
"""Build an asynchronous caching wrapper."""
stats = _Stats()
if cache is None:
async def wrapper(*args: Any, **kwargs: Any) -> Any:
stats.misses += 1
return await fn(*args, **kwargs)
if info:
_attach_noop_info(wrapper, stats)
return wrapper
# Pre-cache method references to avoid attribute lookup per call.
cache_getitem = cache.__getitem__
cache_setitem = cache.__setitem__
cache_setdefault = cache.setdefault
if lock is not None:
async def wrapper(*args: Any, **kwargs: Any) -> Any:
k = key(*args, **kwargs)
async with lock:
try:
result = cache_getitem(k)
except KeyError:
result = _MISS
if result is not _MISS:
stats.hits += 1
return result
stats.misses += 1
v = await fn(*args, **kwargs)
# Inline thread-safe store (was _cache_store_default).
async with lock:
try:
return cache_setdefault(k, v)
except ValueError:
return v
else:
async def wrapper(*args: Any, **kwargs: Any) -> Any:
k = key(*args, **kwargs)
try:
result = cache_getitem(k)
except KeyError:
stats.misses += 1
v = await fn(*args, **kwargs)
try:
cache_setitem(k, v)
except ValueError:
pass
return v
stats.hits += 1
return result
if info:
_attach_cache_info(wrapper, cache, lock, stats, _get_cache_maxsize(cache))
return wrapper
class _no_lock:
"""Dummy context manager when no lock is provided."""
def __enter__(self) -> None:
pass
def __exit__(self, *exc: Any) -> None:
pass
def cached(
cache: Cache | collections.abc.MutableMapping | None,
*,
key: Callable[..., Any] = hashkey,
lock: Any | None = None,
info: bool = False,
) -> Callable:
"""Decorator to wrap a function with a memoizing callable.
Args:
cache: A cache instance (any MutableMapping) or ``None`` to disable.
key: Key function (default ``hashkey``).
lock: A lock object (``threading.Lock`` for sync, ``asyncio.Lock``
for async). The lock is released while the wrapped function
executes.
info: If ``True``, attach ``cache_info()`` and ``cache_clear()``
methods to the wrapper.
"""
def decorator(fn: Callable) -> Callable:
if inspect.iscoroutinefunction(fn):
wrapper = _make_async_wrapper(fn, cache, key, lock, info)
else:
wrapper = _make_sync_wrapper(fn, cache, key, lock, info)
wrapper.cache = cache # type: ignore[attr-defined]
wrapper.cache_key = key # type: ignore[attr-defined]
wrapper.cache_lock = lock # type: ignore[attr-defined]
return functools.update_wrapper(wrapper, fn)
return decorator
# ββ Convenience Decorators βββββββββββββββββββββββββββββββββββββββββββββββββ
def lru_cache(
fn: Callable[..., Any] | None = None,
*,
maxsize: int = 128,
key: Callable[..., Any] = hashkey,
lock: Any | None = None,
info: bool = True,
) -> Callable[..., Any]:
"""LRU cache decorator. Auto-detects sync/async.
Unlike ``functools.lru_cache``, supports TTL (via ``ttl_cache``),
async functions, and explicit lock objects.
Args:
maxsize: Maximum number of cached results.
key: Key function (default ``hashkey``).
lock: Optional lock for thread/async safety.
info: Attach ``cache_info()``/``cache_clear()`` (default ``True``).
"""
def decorator(fn: Callable) -> Callable:
c = LRUCache(maxsize)
return cached(c, key=key, lock=lock, info=info)(fn)
if fn is not None:
return decorator(fn)
return decorator
def fifo_cache(
fn: Callable[..., Any] | None = None,
*,
maxsize: int = 128,
key: Callable[..., Any] = hashkey,
lock: Any | None = None,
info: bool = True,
) -> Callable[..., Any]:
"""FIFO cache decorator. Auto-detects sync/async.
Evicts the oldest inserted item regardless of access pattern.
"""
def decorator(fn: Callable) -> Callable:
c = FIFOCache(maxsize)
return cached(c, key=key, lock=lock, info=info)(fn)
if fn is not None:
return decorator(fn)
return decorator
def lfu_cache(
fn: Callable[..., Any] | None = None,
*,
maxsize: int = 128,
key: Callable[..., Any] = hashkey,
lock: Any | None = None,
info: bool = True,
) -> Callable[..., Any]:
"""LFU cache decorator. Auto-detects sync/async.
Evicts the least frequently accessed item.
"""
def decorator(fn: Callable) -> Callable:
c = LFUCache(maxsize)
return cached(c, key=key, lock=lock, info=info)(fn)
if fn is not None:
return decorator(fn)
return decorator
def ttl_cache(
fn: Callable[..., Any] | None = None,
*,
maxsize: int = 128,
ttl: float = 600,
timer: Callable[[], float] = time.monotonic,
key: Callable[..., Any] = hashkey,
lock: Any | None = None,
info: bool = True,
) -> Callable[..., Any]:
"""TTL cache decorator. Auto-detects sync/async.
Items expire after *ttl* seconds (default 600 = 10 minutes).
Eviction follows LRU order when the cache is full.
"""
def decorator(fn: Callable) -> Callable:
c = TTLCache(maxsize, ttl, timer=timer)
return cached(c, key=key, lock=lock, info=info)(fn)
if fn is not None:
return decorator(fn)
return decorator
# ββ Public API βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
__all__ = [
# Cache classes
"Cache",
"FIFOCache",
"LFUCache",
"LRUCache",
"TTLCache",
# Decorators
"cached",
"fifo_cache",
"lfu_cache",
"lru_cache",
"ttl_cache",
# Key functions
"hashkey",
"methodkey",
"typedkey",
# Stats
"CacheInfo",
]
|