Completed
Push — master ( a8a578...6c485c )
by Ramon
19s queued 10s
created

jsons._cache.clear()   A

Complexity

Conditions 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nop 0
1
"""
2
PRIVATE MODULE: do not import (from) it directly.
3
4
This module contains functionality for caching functions.
5
"""
6
from collections import deque
7
from functools import lru_cache
8
from typing import Callable
9
10
11
class _Wrapper:
12
    """
13
    A wrapper around a function that needs to be cached. This wrapper allows
14
    for a single point from which cache can be cleared.
15
    """
16
    instances = deque([])
17
18
    def __init__(self, wrapped):
19
        self.wrapped = wrapped
20
        self.instances.append(self)
21
22
    @lru_cache(typed=True)
23
    def __call__(self, *args, **kwargs):
24
        return self.wrapped(*args, **kwargs)
25
26
27
def cached(decorated: Callable):
28
    """
29
    Alternative for ``functools.lru_cache``. By decorating a function with
30
    ``cached``, you can clear the cache of that function by calling
31
    ``clear()``.
32
    :param decorated: the decorated function.
33
    :return: a wrapped function.
34
    """
35
    return _Wrapper(decorated)
36
37
38
def clear():
39
    """
40
    Clear all cache of functions that were cached using ``cached``.
41
    :return: None.
42
    """
43
    for w in _Wrapper.instances:
44
        w.__call__.cache_clear()
45