https://github.com/python/cpython/commit/5db331a561059afe7f7fedd75b4bc67550c988cd
commit: 5db331a561059afe7f7fedd75b4bc67550c988cd
branch: main
author: CF Bolz-Tereick <[email protected]>
committer: vstinner <[email protected]>
date: 2026-01-21T15:19:19+01:00
summary:

gh-144030: Add check that argument is callable to Python version of 
functools.lru_cache (#144031)

Co-authored-by: sobolevn <[email protected]>
Co-authored-by: AN Long <[email protected]>

files:
A Misc/NEWS.d/next/Library/2026-01-19-12-48-59.gh-issue-144030.7OK_gB.rst
M Lib/functools.py
M Lib/test/test_functools.py

diff --git a/Lib/functools.py b/Lib/functools.py
index 075418b1605a48..59fc2a8fbf6219 100644
--- a/Lib/functools.py
+++ b/Lib/functools.py
@@ -602,6 +602,9 @@ def decorating_function(user_function):
     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
diff --git a/Lib/test/test_functools.py b/Lib/test/test_functools.py
index 94b469397139c7..3801a82a610891 100644
--- a/Lib/test/test_functools.py
+++ b/Lib/test/test_functools.py
@@ -2157,6 +2157,13 @@ def fib(n):
                 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
index 00000000000000..ef3c02925405b8
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-01-19-12-48-59.gh-issue-144030.7OK_gB.rst
@@ -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`.

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to