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

Co-authored-by: sobolevn <mail@sobolevn.me>
Co-authored-by: AN Long <aisk@users.noreply.github.com>
This commit is contained in:
CF Bolz-Tereick 2026-01-21 15:19:19 +01:00 committed by GitHub
parent 4c7ec78092
commit 5db331a561
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 13 additions and 0 deletions

View 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

View 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):

View File

@ -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`.