Debian Codegraph @

hypothesis-python/src/hypothesis/strategies/_internal/flatmapped.py

raw
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
11 from collections.abc import Callable
12 from typing import Generic, TypeVar
13
14 from hypothesis.internal.conjecture.data import ConjectureData
15 from hypothesis.internal.conjecture.utils import (
16 calc_label_from_callable,
17 combine_labels,
18 )
19 from hypothesis.internal.reflection import get_pretty_function_description
20 from hypothesis.strategies._internal.strategies import (
21 RecurT,
22 SearchStrategy,
23 check_strategy,
24 )
25
26 MappedFrom = TypeVar("MappedFrom")
27 MappedTo = TypeVar("MappedTo")
28
29
30 class FlatMapStrategy(SearchStrategy[MappedTo], Generic[MappedFrom, MappedTo]):
31 def __init__(
32 self,
33 base: SearchStrategy[MappedFrom],
34 expand: Callable[[MappedFrom], SearchStrategy[MappedTo]],
35 ):
36 super().__init__()
37 self.base = base
38 self.expand = expand
39
40 def calc_is_empty(self, recur: RecurT) -> bool:
41 return recur(self.base)
42
43 def calc_label(self) -> int:
44 return combine_labels(
45 self.class_label,
46 self.base.label,
47 calc_label_from_callable(self.expand),
48 )
49
50 def __repr__(self) -> str:
51 if not hasattr(self, "_cached_repr"):
52 self._cached_repr = (
53 f"{self.base!r}.flatmap({get_pretty_function_description(self.expand)})"
54 )
55 return self._cached_repr
56
57 def do_draw(self, data: ConjectureData) -> MappedTo:
58 base = data.draw(self.base)
59 expanded = self.expand(base)
60 check_strategy(expanded)
61 return data.draw(expanded)
62
63 @property
64 def branches(self) -> list[SearchStrategy[MappedTo]]:
65 return [
66 FlatMapStrategy(strategy, expand=self.expand)
67 for strategy in self.base.branches
68 ]