Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

""" 

Simple caching of expensive values. 

""" 

 

from typing import Callable 

from typing import Dict 

from typing import Generic 

from typing import TypeVar 

 

import weakref 

 

Key = TypeVar('Key') 

Value = TypeVar('Value') 

 

 

class Cache(Generic[Key, Value]): # pylint: disable=too-few-public-methods 

""" 

Cache of expensive values. 

""" 

 

_reset_caches: weakref.WeakSet = weakref.WeakSet() 

 

def __init__(self) -> None: 

self._data: Dict[Key, Value] = {} 

Cache._reset_caches.add(self) 

 

def lookup(self, key: Key, compute_value: Callable[[], Value]) -> Value: 

""" 

Lookup a value by its key, computing it only if this is the first lookup. 

""" 

value = self._data.get(key) 

if value is not None: 

return value 

value = compute_value() 

self._data[key] = value 

return value 

 

def __contains__(self, key: Key) -> bool: 

return key in self._data 

 

@staticmethod 

def reset() -> None: 

""" 

Clear all the caches (for tests). 

""" 

for cache in Cache._reset_caches: 

cache._data.clear() # pylint: disable=protected-access