bpo-40504: Allow weakrefs to lru_cache objects (GH-19938)
diff --git a/Lib/test/test_functools.py b/Lib/test/test_functools.py
index 9503f40..b3893a1 100644
--- a/Lib/test/test_functools.py
+++ b/Lib/test/test_functools.py
@@ -14,6 +14,8 @@
import unittest
import unittest.mock
import os
+import weakref
+import gc
from weakref import proxy
import contextlib
@@ -1938,6 +1940,35 @@
return 1
self.assertEqual(f.cache_parameters(), {'maxsize': 1000, "typed": True})
+ def test_lru_cache_weakrefable(self):
+ @self.module.lru_cache
+ def test_function(x):
+ return x
+
+ class A:
+ @self.module.lru_cache
+ def test_method(self, x):
+ return (self, x)
+
+ @staticmethod
+ @self.module.lru_cache
+ def test_staticmethod(x):
+ return (self, x)
+
+ refs = [weakref.ref(test_function),
+ weakref.ref(A.test_method),
+ weakref.ref(A.test_staticmethod)]
+
+ for ref in refs:
+ self.assertIsNotNone(ref())
+
+ del A
+ del test_function
+ gc.collect()
+
+ for ref in refs:
+ self.assertIsNone(ref())
+
@py_functools.lru_cache()
def py_cached_func(x, y):