8

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)
user308827
  • 21,227
  • 87
  • 254
  • 417

5 Answers5

18

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.

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
6

You need to import lru_cache before using it:

from functools import lru_cache

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

Or alternatively refer to it with full name when importing functools:

import functools

@functools.lru_cache(maxsize=None)
def fib(n):
niemmi
  • 17,113
  • 7
  • 35
  • 42
2

The import line is not included in the question, but it should be:

from functools import lru_cache

Alternatively, the function decorator could be changed to:

@functools.lru_cache(maxsize=None)
Lex Scarisbrick
  • 1,540
  • 1
  • 24
  • 31
2

Another side point, according to documentation is that:

If maxsize is set to None, the LRU feature is disabled and the cache can grow without bound. The LRU feature performs best when maxsize is a power-of-two.

Documentation Example

import functools
import urllib
import requests

    @functools.lru_cache(maxsize=32)
    def get_pep(num):
        'Retrieve text of a Python Enhancement Proposal'
        resource = 'http://www.python.org/dev/peps/pep-%04d/' % num
        try:
            with urllib.request.urlopen(resource) as s:
                return s.read()
        except urllib.error.HTTPError:
            return 'Not Found'


    for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
        pep = get_pep(n)
        print(n, len(pep))

    print(get_pep.cache_info())

Output

8 106439
290 59766
308 56972
320 49551
8 106439
218 46795
320 49551
279 48553
289 50882
320 49551
9991 9
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
Emma
  • 27,428
  • 11
  • 44
  • 69
  • 1
    can we use ```@functools.lru_cache(maxsize=32)``` for multiple function in same file? – Mayur Feb 03 '20 at 12:42
0

If you are trying to use LRU cache for asynchronous function it won't work. Try async-cache . It supports async type functions in python also you can use user defined datatypes along with primitive datatypes as params in cached function. This is not supported in functools.lru_cache

Rajat Singh
  • 300
  • 2
  • 8