brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's functools.lru_cache remembers results so slow functions run once

Python
~/tips/tip-python-functools-lru-cache

from functools import lru_cache

Caches the results of a Python function, so repeated calls with the same arguments are instant.

A function that does the same slow work again and again, with the same input, is an easy win. Python can remember the answers for you.

from functools import lru_cache

@lru_cache(maxsize=128)
def lookup(host):
    return slow_dns_or_api_call(host)

The first call with a given argument runs the function; later calls with the same argument return the stored result. maxsize limits how many results are kept; the least recently used ones go first. Since Python 3.9 there is also @cache, which is the same as lru_cache(maxsize=None): no limit at all.

You can see whether it helps:

print(lookup.cache_info())
# CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)

Lots of hits means the cache is doing its job. lookup.cache_clear() empties it, for example after you know the underlying data changed.

Caveats, and the docs list several. The arguments must be hashable, so a list as argument raises an error; pass a tuple instead. It makes no sense for functions with side effects, or for ones that should give a fresh answer each time, like anything based on time() or random(). f(a=1, b=2) and f(b=2, a=1) can end up as two separate entries. And on a method, self is part of the cache key, so every object gets its own entries. For a long-running service with changing data, I’d rather use a cache with an expiry time than this one.

Further reading: Python docs: functools

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link