Skip to content

API

Core functionality.

lru_cache(expires_after=None, *lru_args, **lru_kwargs)

LRU caching with expiration period.

Acts as a drop-in replacement of functools.lru_cache. Arguments valid for functools.lru_cache can also be passed.

Parameters:

Name Type Description Default
expires_after Optional[int]

number of seconds after which to invalidate cache - None will never invalidate based on time. Convenience variables MINUTES, HOURS and DAYS are available (using lru_cache(expires_after=2 * DAYS))

None
args

functools.lru_cache's positional arguments

required
kwargs

functools.lru_cache's keyword arguments

required

Returns:

Type Description
Callable

cached function

Source code in expiring_lru_cache/__init__.py
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
67
68
69
70
71
72
def lru_cache(
    expires_after: Optional[int] = None,
    *lru_args: Union[int, bool],
    **lru_kwargs: Union[int, bool],
) -> Callable:
    """
    LRU caching with expiration period.

    Acts as a drop-in replacement of `functools.lru_cache`. Arguments valid for
     `functools.lru_cache` can also be passed.
    :param expires_after: number of seconds after which to invalidate cache - `None`
     will never invalidate based on time. Convenience variables `MINUTES`, `HOURS`
     and `DAYS` are available (using `lru_cache(expires_after=2 * DAYS)`)
    :param args: `functools.lru_cache`'s positional arguments
    :param kwargs: `functools.lru_cache`'s keyword arguments
    :return: cached function
    """

    def decorate(func: Callable) -> Callable:
        cached_func = _init_cache(func, expires_after, *lru_args, **lru_kwargs)

        @functools.wraps(func)
        def wrapper(*args: Union[int, bool], **kwargs: Union[int, bool]) -> Callable:
            nonlocal cached_func
            if _expired(cached_func):
                logging.debug("Resetting cache")
                cached_func = _init_cache(func, expires_after, *lru_args, **lru_kwargs)
            return cached_func(*args, **kwargs)

        wrapper.cache_info = lambda: cached_func.cache_info()
        return wrapper

    return decorate