bpo-40571: Make lru_cache(maxsize=None) more discoverable (GH-20019)
diff --git a/Lib/functools.py b/Lib/functools.py
index f05b106..87c7d87 100644
--- a/Lib/functools.py
+++ b/Lib/functools.py
@@ -10,7 +10,7 @@
# See C source code for _functools credits/copyright
__all__ = ['update_wrapper', 'wraps', 'WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES',
- 'total_ordering', 'cmp_to_key', 'lru_cache', 'reduce',
+ 'total_ordering', 'cache', 'cmp_to_key', 'lru_cache', 'reduce',
'TopologicalSorter', 'CycleError',
'partial', 'partialmethod', 'singledispatch', 'singledispatchmethod',
'cached_property']
@@ -889,6 +889,15 @@
################################################################################
+### cache -- simplified access to the infinity cache
+################################################################################
+
+def cache(user_function, /):
+ 'Simple lightweight unbounded cache. Sometimes called "memoize".'
+ return lru_cache(maxsize=None)(user_function)
+
+
+################################################################################
### singledispatch() - single-dispatch generic function decorator
################################################################################
diff --git a/Lib/test/test_functools.py b/Lib/test/test_functools.py
index b3893a1..e122fe0 100644
--- a/Lib/test/test_functools.py
+++ b/Lib/test/test_functools.py
@@ -1432,6 +1432,25 @@
self.assertEqual(run1, run2)
+class TestCache:
+ # This tests that the pass-through is working as designed.
+ # The underlying functionality is tested in TestLRU.
+
+ def test_cache(self):
+ @self.module.cache
+ def fib(n):
+ if n < 2:
+ return n
+ return fib(n-1) + fib(n-2)
+ self.assertEqual([fib(n) for n in range(16)],
+ [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610])
+ self.assertEqual(fib.cache_info(),
+ self.module._CacheInfo(hits=28, misses=16, maxsize=None, currsize=16))
+ fib.cache_clear()
+ self.assertEqual(fib.cache_info(),
+ self.module._CacheInfo(hits=0, misses=0, maxsize=None, currsize=0))
+
+
class TestLRU:
def test_lru(self):