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
12
13from hypothesis.configuration import check_sideeffect_during_initialization
14from hypothesis.errors import InvalidArgument
15from hypothesis.internal.reflection import get_pretty_function_description
16from hypothesis.strategies._internal.strategies import SearchStrategy, check_strategy
17
18
19class DeferredStrategy(SearchStrategy):
20 """A strategy which may be used before it is fully defined."""
21
22 def __init__(self, definition):
23 super().__init__()
24 self.__wrapped_strategy = None
25 self.__in_repr = False
26 self.__definition = definition
27
28 @property
29 def wrapped_strategy(self):
30 if self.__wrapped_strategy is None:
31 check_sideeffect_during_initialization("deferred evaluation of {!r}", self)
32
33 if not inspect.isfunction(self.__definition):
34 raise InvalidArgument(
35 f"Expected definition to be a function but got {self.__definition!r} "
36 f"of type {type(self.__definition).__name__} instead."
37 )
38 result = self.__definition()
39 if result is self:
40 raise InvalidArgument("Cannot define a deferred strategy to be itself")
41 check_strategy(result, "definition()")
42 self.__wrapped_strategy = result
43 self.__definition = None
44 return self.__wrapped_strategy
45
46 @property
47 def branches(self):
48 return self.wrapped_strategy.branches
49
50 @property
51 def supports_find(self):
52 return self.wrapped_strategy.supports_find
53
54 def calc_label(self):
55 """Deferred strategies don't have a calculated label, because we would
56 end up having to calculate the fixed point of some hash function in
57 order to calculate it when they recursively refer to themself!
58
59 The label for the wrapped strategy will still appear because it
60 will be passed to draw.
61 """
62 # This is actually the same as the parent class implementation, but we
63 # include it explicitly here in order to document that this is a
64 # deliberate decision.
65 return self.class_label
66
67 def calc_is_empty(self, recur):
68 return recur(self.wrapped_strategy)
69
70 def calc_has_reusable_values(self, recur):
71 return recur(self.wrapped_strategy)
72
73 def __repr__(self):
74 if self.__wrapped_strategy is not None:
75 if self.__in_repr:
76 return f"(deferred@{id(self)!r})"
77 try:
78 self.__in_repr = True
79 return repr(self.__wrapped_strategy)
80 finally:
81 self.__in_repr = False
82 else:
83 description = get_pretty_function_description(self.__definition)
84 return f"deferred({description})"
85
86 def do_draw(self, data):
87 return data.draw(self.wrapped_strategy)