cache.py 1.02 KB
Newer Older
1
import os
2
from collections.abc import Hashable
3
4
from functools import partial
from itertools import chain
5

6
7
8
9
10
try:
    from functools import lru_cache as memorycache
except ImportError:
    from backports.functools_lru_cache import lru_cache as memorycache

Markus Holzer's avatar
Markus Holzer committed
11
12
from joblib import Memory
from appdirs import user_cache_dir
13

Markus Holzer's avatar
Markus Holzer committed
14
15
16
17
18
19
if 'PYSTENCILS_CACHE_DIR' in os.environ:
    cache_dir = os.environ['PYSTENCILS_CACHE_DIR']
else:
    cache_dir = user_cache_dir('pystencils')
disk_cache = Memory(cache_dir, verbose=False).cache
disk_cache_no_fallback = disk_cache
20

21

22
23
24
25
26
27
28
29
30
31
32
33
34
def _wrapper(wrapped_func, cached_func, *args, **kwargs):
    if all(isinstance(a, Hashable) for a in chain(args, kwargs.values())):
        return cached_func(*args, **kwargs)
    else:
        return wrapped_func(*args, **kwargs)


def memorycache_if_hashable(maxsize=128, typed=False):
    def wrapper(func):
        return partial(_wrapper, func, memorycache(maxsize, typed)(func))

    return wrapper

35
# Disable memory cache:
Martin Bauer's avatar
Martin Bauer committed
36
37
# disk_cache = lambda o: o
# disk_cache_no_fallback = lambda o: o