Debian Codegraph @

hypothesis-python/docs/how-to/type-strategies.rst

raw
1 Write type hints for strategies
2 ===============================
3
4 Hypothesis provides type hints for all strategies and functions which return a strategy:
5
6 .. code-block:: python
7
8 from hypothesis import strategies as st
9
10 reveal_type(st.integers())
11 # SearchStrategy[int]
12
13 reveal_type(st.lists(st.integers()))
14 # SearchStrategy[list[int]]
15
16 |SearchStrategy| is the type of a strategy. It is parametrized by the type of the example it generates. You can use it to write type hints for your functions which return a strategy:
17
18 .. code-block:: python
19
20 from hypothesis import strategies as st
21 from hypothesis.strategies import SearchStrategy
22
23 # returns a strategy for "normal" numbers
24 def numbers() -> SearchStrategy[int | float]:
25 return st.integers() | st.floats(allow_nan=False, allow_infinity=False)
26
27 It's worth pointing out the distinction between a strategy, and a function that returns a strategy. |st.integers| is a function which returns a strategy, and that strategy has type ``SearchStrategy[int]``. The function ``st.integers`` therefore has type ``Callable[..., SearchStrategy[int]]``, while the value ``s = st.integers()`` has type ``SearchStrategy[int]``.
28
29
30 Type hints for |st.composite|
31 -----------------------------
32
33 When writing type hints for strategies defined with |st.composite|, use the type of the returned value (not ``SearchStrategy``):
34
35 .. code-block:: python
36
37 @st.composite
38 def ordered_pairs(draw) -> tuple[int, int]:
39 n1 = draw(st.integers())
40 n2 = draw(st.integers(min_value=n1))
41 return (n1, n2)
42
43 Type variance of |SearchStrategy|
44 ---------------------------------
45
46 |SearchStrategy| is covariant, meaning that if ``B < A`` then ``SearchStrategy[B] < SearchStrategy[A]``. In other words, the strategy ``st.from_type(Dog)`` is a subtype of the strategy ``st.from_type(Animal)``.