Skip to content

Commit 5db331a

Browse files
cfbolzsobolevnaisk
authored
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>
1 parent 4c7ec78 commit 5db331a

File tree

3 files changed

+13
-0
lines changed

3 files changed

+13
-0
lines changed

Lib/functools.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -602,6 +602,9 @@ def decorating_function(user_function):
602602
return decorating_function
603603

604604
def _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo):
605+
if not callable(user_function):
606+
raise TypeError("the first argument must be callable")
607+
605608
# Constants shared by all lru cache instances:
606609
sentinel = object() # unique object used to signal cache misses
607610
make_key = _make_key # build a key from the function arguments

Lib/test/test_functools.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2157,6 +2157,13 @@ def fib(n):
21572157
with self.assertRaises(RecursionError):
21582158
fib(support.exceeds_recursion_limit())
21592159

2160+
def test_lru_checks_arg_is_callable(self):
2161+
with self.assertRaisesRegex(
2162+
TypeError,
2163+
"the first argument must be callable",
2164+
):
2165+
self.module.lru_cache(1)('hello')
2166+
21602167

21612168
@py_functools.lru_cache()
21622169
def py_cached_func(x, y):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
The Python implementation of :func:`functools.lru_cache` differed from the
2+
default C implementation in that it did not check that its argument is
3+
callable. This discrepancy is now fixed and both raise a :exc:`TypeError`.

0 commit comments

Comments
 (0)