File: _imcache.py

package info (click to toggle)
isbnlib 3.9.3-1
  • links: PTS
  • area: main
  • in suites: buster
  • size: 596 kB
  • sloc: python: 4,575; makefile: 4
file content (46 lines) | stat: -rw-r--r-- 1,023 bytes parent folder | download | duplicates (2)
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
# -*- coding: utf-8 -*-
"""Read and write to a dict-like cache."""

from collections import MutableMapping


class IMCache(MutableMapping):
    """Read and write to a dict-like cache."""

    MAXLEN = 1000

    def __init__(self, maxlen=MAXLEN, *a, **k):
        self.filepath = 'IN MEMORY'
        self.maxlen = maxlen
        self.d = dict(*a, **k)
        while len(self) > maxlen:  # pragma: no cache
            self.popitem()

    def __iter__(self):
        return iter(self.d)

    def __len__(self):
        return len(self.d)

    def __getitem__(self, k):
        return self.d[k]

    def __setitem__(self, k, v):
        if k not in self and len(self) == self.maxlen:
            self.popitem()
        self.d[k] = v

    def __delitem__(self, k):
        del self.d[k]

    def __bool__(self):
        return len(self) != 0

    # For PY2 compatibility
    __nonzero__ = __bool__

    def __call__(self, k):
        try:
            return self.__getitem__(k)
        except KeyError:
            return None