Completed
Pull Request — master (#65)
by Ramon
01:41
created

jsons._cache   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 17
dl 0
loc 44
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A _Wrapper.__init__() 0 3 1
A _Wrapper.__call__() 0 3 1

2 Functions

Rating   Name   Duplication   Size   Complexity  
A cached() 0 9 1
A clear() 0 7 2
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.
14
    """
15
    instances = deque([])
16
17
    def __init__(self, wrapped):
18
        self.wrapped = wrapped
19
        self.instances.append(self)
20
21
    @lru_cache(typed=True)
22
    def __call__(self, *args, **kwargs):
23
        return self.wrapped(*args, **kwargs)
24
25
26
def cached(decorated: Callable):
27
    """
28
    Alternative for ``functools.lru_cache``. By decorating a function with
29
    ``cached``, you can clear the cache of that function by calling
30
    ``clear()``.
31
    :param decorated: the decorated function.
32
    :return: a wrapped function.
33
    """
34
    return _Wrapper(decorated)
35
36
37
def clear():
38
    """
39
    Clear all cache of functions that were cached using ``cached``.
40
    :return: None.
41
    """
42
    for w in _Wrapper.instances:
43
        w.__call__.cache_clear()
44