1# This file is part of Hypothesis, which may be found at
2# https://github.com/HypothesisWorks/hypothesis/
3#
4# Copyright the Hypothesis Authors.
5# Individual contributors are listed in AUTHORS.rst and the git log.
6#
7# This Source Code Form is subject to the terms of the Mozilla Public License,
8# v. 2.0. If a copy of the MPL was not distributed with this file, You can
9# obtain one at https://mozilla.org/MPL/2.0/.
10
11import inspect
12from collections.abc import Callable, Sequence
13
14from hypothesis.configuration import check_sideeffect_during_initialization
15from hypothesis.errors import InvalidArgument
16from hypothesis.internal.conjecture.data import ConjectureData
17from hypothesis.internal.reflection import get_pretty_function_description
18from hypothesis.strategies._internal.strategies import (
19 Ex,
20 RecurT,
21 SearchStrategy,
22 check_strategy,
23)
24
25
26class DeferredStrategy(SearchStrategy[Ex]):
27 """A strategy which may be used before it is fully defined."""
28
29 def __init__(self, definition: Callable[[], SearchStrategy[Ex]]):
30 super().__init__()
31 self.__wrapped_strategy: SearchStrategy[Ex] | None = None
32 self.__in_repr: bool = False
33 self.__definition: Callable[[], SearchStrategy[Ex]] | None = definition
34
35 @property
36 def wrapped_strategy(self) -> SearchStrategy[Ex]:
37 # we assign this before entering the condition to avoid a race condition
38 # under threading. See issue #4523.
39 definition = self.__definition
40 if self.__wrapped_strategy is None:
41 check_sideeffect_during_initialization("deferred evaluation of {!r}", self)
42
43 if not inspect.isfunction(definition):
44 raise InvalidArgument(
45 f"Expected definition to be a function but got {definition!r} "
46 f"of type {type(definition).__name__} instead."
47 )
48 result = definition()
49 if result is self:
50 raise InvalidArgument("Cannot define a deferred strategy to be itself")
51 check_strategy(result, "definition()")
52 self.__wrapped_strategy = result
53 self.__definition = None
54 return self.__wrapped_strategy
55
56 @property
57 def branches(self) -> Sequence[SearchStrategy[Ex]]:
58 return self.wrapped_strategy.branches
59
60 def calc_label(self) -> int:
61 """Deferred strategies don't have a calculated label, because we would
62 end up having to calculate the fixed point of some hash function in
63 order to calculate it when they recursively refer to themself!
64
65 The label for the wrapped strategy will still appear because it
66 will be passed to draw.
67 """
68 # This is actually the same as the parent class implementation, but we
69 # include it explicitly here in order to document that this is a
70 # deliberate decision.
71 return self.class_label
72
73 def calc_is_empty(self, recur: RecurT) -> bool:
74 return recur(self.wrapped_strategy)
75
76 def calc_has_reusable_values(self, recur: RecurT) -> bool:
77 return recur(self.wrapped_strategy)
78
79 def __repr__(self) -> str:
80 if self.__wrapped_strategy is not None:
81 if self.__in_repr:
82 return f"(deferred@{id(self)!r})"
83 try:
84 self.__in_repr = True
85 return repr(self.__wrapped_strategy)
86 finally:
87 self.__in_repr = False
88 else:
89 description = get_pretty_function_description(self.__definition)
90 return f"deferred({description})"
91
92 def do_draw(self, data: ConjectureData) -> Ex:
93 return data.draw(self.wrapped_strategy)