]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-144030: Add check that argument is callable to Python version of functools.lru_cac...
authorCF Bolz-Tereick <cfbolz@gmx.de>
Wed, 21 Jan 2026 14:19:19 +0000 (15:19 +0100)
committerGitHub <noreply@github.com>
Wed, 21 Jan 2026 14:19:19 +0000 (15:19 +0100)
Co-authored-by: sobolevn <mail@sobolevn.me>
Co-authored-by: AN Long <aisk@users.noreply.github.com>
Lib/functools.py
Lib/test/test_functools.py
Misc/NEWS.d/next/Library/2026-01-19-12-48-59.gh-issue-144030.7OK_gB.rst [new file with mode: 0644]

index 075418b1605a4874d78bdf54f41dd5a8508480fa..59fc2a8fbf6219e15c5c12f5f0b24830e8cc4984 100644 (file)
@@ -602,6 +602,9 @@ def lru_cache(maxsize=128, typed=False):
     return decorating_function
 
 def _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo):
+    if not callable(user_function):
+        raise TypeError("the first argument must be callable")
+
     # Constants shared by all lru cache instances:
     sentinel = object()          # unique object used to signal cache misses
     make_key = _make_key         # build a key from the function arguments
index 94b469397139c7f6182e13af9451816518bc1161..3801a82a6108914f611bdfa91b807ccfb025d9fb 100644 (file)
@@ -2157,6 +2157,13 @@ class TestLRU:
                 with self.assertRaises(RecursionError):
                     fib(support.exceeds_recursion_limit())
 
+    def test_lru_checks_arg_is_callable(self):
+        with self.assertRaisesRegex(
+            TypeError,
+            "the first argument must be callable",
+        ):
+            self.module.lru_cache(1)('hello')
+
 
 @py_functools.lru_cache()
 def py_cached_func(x, y):
diff --git a/Misc/NEWS.d/next/Library/2026-01-19-12-48-59.gh-issue-144030.7OK_gB.rst b/Misc/NEWS.d/next/Library/2026-01-19-12-48-59.gh-issue-144030.7OK_gB.rst
new file mode 100644 (file)
index 0000000..ef3c029
--- /dev/null
@@ -0,0 +1,3 @@
+The Python implementation of :func:`functools.lru_cache` differed from the
+default C implementation in that it did not check that its argument is
+callable. This discrepancy is now fixed and both raise a :exc:`TypeError`.