Skip to content

Commit dfb720e

Browse files
committed
use WeakKeyDictionary instead of lru cache
1 parent cc1aee8 commit dfb720e

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

hypothesis-python/src/hypothesis/internal/reflection.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,15 @@
2121
import textwrap
2222
import types
2323
import warnings
24-
from functools import lru_cache, partial, wraps
24+
from functools import partial, wraps
2525
from io import StringIO
2626
from keyword import iskeyword
2727
from random import _inst as global_random_instance
2828
from tokenize import COMMENT, detect_encoding, generate_tokens, untokenize
2929
from types import ModuleType
30-
from typing import TYPE_CHECKING, Any, Callable
30+
from typing import TYPE_CHECKING, Any, Callable, MutableMapping
3131
from unittest.mock import _patch as PatchType
32+
from weakref import WeakKeyDictionary
3233

3334
from hypothesis.errors import HypothesisWarning
3435
from hypothesis.internal.compat import PYPY, is_typed_named_tuple
@@ -39,6 +40,7 @@
3940
from hypothesis.strategies._internal.strategies import T
4041

4142
READTHEDOCS = os.environ.get("READTHEDOCS", None) == "True"
43+
LAMBDA_SOURCE_CACHE: MutableMapping[Callable, str] = WeakKeyDictionary()
4244

4345

4446
def is_mock(obj):
@@ -303,8 +305,7 @@ def visit_Lambda(self, node):
303305
SPACE_PRECEDES_CLOSE_BRACKET = re.compile(r" \)")
304306

305307

306-
@lru_cache(maxsize=1024)
307-
def extract_lambda_source(f):
308+
def _extract_lambda_source(f):
308309
"""Extracts a single lambda expression from the string source. Returns a
309310
string indicating an unknown body if it gets confused in any way.
310311
@@ -440,6 +441,17 @@ def extract_lambda_source(f):
440441
return source.strip()
441442

442443

444+
def extract_lambda_source(f):
445+
try:
446+
return LAMBDA_SOURCE_CACHE[f]
447+
except KeyError:
448+
pass
449+
450+
source = _extract_lambda_source(f)
451+
LAMBDA_SOURCE_CACHE[f] = source
452+
return source
453+
454+
443455
def get_pretty_function_description(f):
444456
if isinstance(f, partial):
445457
return pretty(f)
@@ -493,7 +505,7 @@ def repr_call(f, args, kwargs, *, reorder=True):
493505
if repr_len > 30000:
494506
warnings.warn(
495507
"Generating overly large repr. This is an expensive operation, and with "
496-
f"a length of {repr_len//1000} kB is is unlikely to be useful. Use -Wignore "
508+
f"a length of {repr_len//1000} kB is unlikely to be useful. Use -Wignore "
497509
"to ignore the warning, or -Werror to get a traceback.",
498510
HypothesisWarning,
499511
stacklevel=2,

0 commit comments

Comments
 (0)