Skip to content

Commit

Permalink
use WeakKeyDictionary instead of lru cache
Browse files Browse the repository at this point in the history
  • Loading branch information
tybug committed May 3, 2024
1 parent cc1aee8 commit e4f7909
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions hypothesis-python/src/hypothesis/internal/reflection.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from types import ModuleType
from typing import TYPE_CHECKING, Any, Callable
from unittest.mock import _patch as PatchType
from weakref import WeakKeyDictionary

from hypothesis.errors import HypothesisWarning
from hypothesis.internal.compat import PYPY, is_typed_named_tuple
Expand All @@ -39,6 +40,7 @@
from hypothesis.strategies._internal.strategies import T

READTHEDOCS = os.environ.get("READTHEDOCS", None) == "True"
PRETTY_FUNCTION_CACHE = WeakKeyDictionary()


def is_mock(obj):
Expand Down Expand Up @@ -440,11 +442,7 @@ def extract_lambda_source(f):
return source.strip()


def get_pretty_function_description(f):
if isinstance(f, partial):
return pretty(f)
if not hasattr(f, "__name__"):
return repr(f)
def _pretty_function_description(f):
name = f.__name__
if name == "<lambda>":
return extract_lambda_source(f)
Expand All @@ -462,6 +460,23 @@ def get_pretty_function_description(f):
return name


def get_pretty_function_description(f):
# handle non-hashable cases before the cache
if isinstance(f, partial):
return pretty(f)
if not hasattr(f, "__name__"):
return repr(f)

try:
return PRETTY_FUNCTION_CACHE[f]
except KeyError:
pass

description = _pretty_function_description(f)
PRETTY_FUNCTION_CACHE[f] = description
return description


def nicerepr(v):
if inspect.isfunction(v):
return get_pretty_function_description(v)
Expand Down Expand Up @@ -493,7 +508,7 @@ def repr_call(f, args, kwargs, *, reorder=True):
if repr_len > 30000:
warnings.warn(
"Generating overly large repr. This is an expensive operation, and with "
f"a length of {repr_len//1000} kB is is unlikely to be useful. Use -Wignore "
f"a length of {repr_len//1000} kB is unlikely to be useful. Use -Wignore "
"to ignore the warning, or -Werror to get a traceback.",
HypothesisWarning,
stacklevel=2,
Expand Down

0 comments on commit e4f7909

Please sign in to comment.