aboutsummaryrefslogtreecommitdiff
path: root/cachetools/rr.py
blob: 5119c48a8fbabc91b70b1f10130d29d661cf03e8 (plain)
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
import random

from .cache import Cache
from .decorators import cachedfunc
from .lock import RLock


class RRCache(Cache):
    """Random Replacement (RR) cache implementation."""

    def __init__(self, maxsize, choice=random.choice, missing=None,
                 getsizeof=None):
        Cache.__init__(self, maxsize, missing, getsizeof)
        self.__choice = choice

    def popitem(self):
        """Remove and return a random `(key, value)` pair."""
        try:
            key = self.__choice(list(self))
        except IndexError:
            raise KeyError('cache is empty')
        return (key, self.pop(key))

    @property
    def choice(self):
        """The `choice` function used by the cache."""
        return self.__choice


def rr_cache(maxsize=128, choice=random.choice, typed=False, getsizeof=None,
             lock=RLock):
    """Decorator to wrap a function with a memoizing callable that saves
    up to `maxsize` results based on a Random Replacement (RR)
    algorithm.

    """
    return cachedfunc(RRCache(maxsize, choice, getsizeof), typed, lock)