Search code examples
pythonlrufunctools

Usage for lru cache in functools


I want to use lru_cache in my code, however, I get this error:

NameError: name 'lru_cache' is not defined

I do have an import functools in my code but that does not help

Example code is here:

https://docs.python.org/3/library/functools.html

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

Solution

  • If you really just wrote import functools, then that's not enough. You need to either import the lru_cache symbol with from functools import lru_cache, or you need to qualify the name when you attempt to use it, like @functools.lru_cache.

    There's nothing special about the functools module in this respect. All modules work this way. You've probably noticed when you've imported other modules and used other functions.