-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
cache.py
66 lines (47 loc) · 1.33 KB
/
cache.py
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""Caching facility for Diofant."""
import functools
import os
import typing
from .evaluate import global_evaluate
# global cache registry: [] of (item, {})
CACHE: typing.List[typing.Any] = []
def print_cache():
"""Print cache content."""
for item in CACHE:
print(item.__qualname__, item.cache_info())
def clear_cache():
"""Clear cache content."""
for item in CACHE:
item.cache_clear()
USE_CACHE = os.getenv('DIOFANT_USE_CACHE', 'True') == 'True'
def cacheit(f, maxsize=None):
"""Caching decorator.
The result of cached function must be *immutable*.
Examples
========
>>> @cacheit
... def f(a, b):
... print(a, b)
... return a + b
>>> f(x, y)
x y
x + y
>>> f(x, y)
x + y
"""
if USE_CACHE:
cfunc = functools.lru_cache(maxsize=maxsize, typed=True)(f)
def wrapper(*args, **kwargs):
try:
if global_evaluate[0] and kwargs.get('evaluate', True):
return cfunc(*args, **kwargs)
except TypeError:
pass
return f(*args, **kwargs)
wrapper.cache_info = cfunc.cache_info
wrapper.cache_clear = cfunc.cache_clear
functools.update_wrapper(wrapper, f)
CACHE.append(wrapper)
return wrapper
else:
return f