Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python importError name lru_cache

While running the code below, I am getting the error that Python cannot import lru_cache. However, this happens with every import (math, etc...). I've tried every single tutorial I can find on the internet to try to get this thing to work. I've reinstalled Python. Pip and homebrew are installed as well.

#!usr/bin
from functools import lru_cache
import math

fibonacci_cache = {}

@lru_cache(maxsize = 1000)
def fibonacci(n):

    if n == 1:
        return 1
    elif n == 2:
        return 1
    elif n > 2:
        return fibonacci(n-1) + fibonacci(n-2)

for n in range(1, 501):
    print(n, ":", fibonacci(n))

The error:

Kapoyas-MacBook-Pro:bin Keaton$ python python.py
Traceback (most recent call last):
File "python.py", line 2, in <module>
from functools import lru_cache
ImportError: cannot import name lru_cache
like image 948
KeatonBenning Avatar asked Aug 22 '17 13:08

KeatonBenning


1 Answers

Due to version(python 2.7 or 3.x), as provided in the documentation consider using:

try:
    from functools import lru_cache
except ImportError:
    from backports.functools_lru_cache import lru_cache
like image 170
Taiwotman Avatar answered Oct 17 '22 11:10

Taiwotman