All the solutions I managed to find are only on lru_cache
. But in my case dir(functools)
shows that that very lru_cache
does reside in functools
while cache
does not! How can I solve this?
Asked
Active
Viewed 2.2k times
23

Kaiyakha
- 1,463
- 1
- 6
- 19
-
1`cache` is Python 3.9 pretty sure – Joshua Nixon Mar 28 '21 at 22:20
-
@JoshuaNixon missed the spot, I googled the error itself – Kaiyakha Mar 30 '21 at 22:45
-
Are you trying ``from functools import cache'' at GoogleColab ? If yes, maybe it is better to use ``from functools import lru_cache'', then call @lru_cache(maxsize=None) . This worked for me (with GoogleColab - that is currently using Python 3.7). – Diving May 05 '22 at 19:10
2 Answers
44
The documentation for functools.cache
states that it's only available from Python 3.9 onwards. If you're using an earlier version then the documentation also states that it's the same as using lru_cache(maxsize=None)
, so that's probably your best option.

Kemp
- 3,467
- 1
- 18
- 27
-
2The source on `cache` was not that brand new so that I could've thought it is a new feature of `functools`. Didn't think 3.9 is so old by now. – Kaiyakha Mar 28 '21 at 22:24
-
1@Kaiyakha Python 3.9 is the latest released branch. `cache` *is* a new feature of `functools` as of Python 3.9, as I said. If you are using an earlier version it will not be available and you must use `lru_cache` instead. – Kemp Mar 28 '21 at 22:26
-
-4
from functools import lru_cache
@lru_cache(maxsize=128)
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
def main():
for i in range(1000):
print(i, fib(i))
print('Done')
if __name__ == '__main__':
main()

Robert
- 7,394
- 40
- 45
- 64
-
As per my existing answer the documentation states that `cache` is equivalent to `lru_cache` with a `maxsize` of None, not 128. Additionally, please do not post code-only answers - explain what the code is showing in terms of answering the question. Printing the Fibonacci Sequence was not part of the question. – Kemp Feb 14 '22 at 19:23