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

jsons._cache._Wrapper.__call__()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nop 3
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