|
24 | 24 | from decimal import Context, Decimal, localcontext |
25 | 25 | from fractions import Fraction |
26 | 26 | from functools import reduce |
27 | | -from inspect import Parameter, getfullargspec, isabstract, isclass, signature |
| 27 | +from inspect import Parameter, Signature, getfullargspec, isabstract, isclass, signature |
28 | 28 | from types import FunctionType |
29 | 29 | from typing import ( |
30 | 30 | Any, |
|
111 | 111 | from hypothesis.strategies._internal.utils import cacheable, defines_strategy |
112 | 112 | from hypothesis.utils.conventions import InferType, infer, not_set |
113 | 113 |
|
| 114 | +try: |
| 115 | + from typing import Protocol |
| 116 | +except ImportError: # < py3.8 |
| 117 | + Protocol = object # type: ignore[assignment] |
| 118 | + |
114 | 119 | UniqueBy = Union[Callable[[Ex], Hashable], Tuple[Callable[[Ex], Hashable], ...]] |
115 | 120 |
|
116 | 121 |
|
@@ -1404,6 +1409,33 @@ def calc_label(self): |
1404 | 1409 | return calc_label_from_cls(self.definition) |
1405 | 1410 |
|
1406 | 1411 |
|
| 1412 | +class DrawFn(Protocol): |
| 1413 | + """This type only exists so that you can write type hints for functions |
| 1414 | + decorated with :func:`@composite <hypothesis.strategies.composite>`. |
| 1415 | +
|
| 1416 | + .. code-block:: python |
| 1417 | +
|
| 1418 | + @composite |
| 1419 | + def list_and_index(draw: DrawFn) -> Tuple[int, str]: |
| 1420 | + i = draw(integers()) # type inferred as 'int' |
| 1421 | + s = draw(text()) # type inferred as 'str' |
| 1422 | +
|
| 1423 | + """ |
| 1424 | + |
| 1425 | + def __init__(self): |
| 1426 | + raise TypeError("Protocols cannot be instantiated") # pragma: no cover |
| 1427 | + |
| 1428 | + # On Python 3.8+, Protocol overrides our signature for __init__, |
| 1429 | + # so we override it right back to make the docs look nice. |
| 1430 | + __signature__: Signature = Signature(parameters=[]) |
| 1431 | + |
| 1432 | + # We define this as a callback protocol because a simple typing.Callable is |
| 1433 | + # insufficient to fully represent the interface, due to the optional `label` |
| 1434 | + # parameter. |
| 1435 | + def __call__(self, strategy: SearchStrategy[Ex], label: object = None) -> Ex: |
| 1436 | + raise NotImplementedError |
| 1437 | + |
| 1438 | + |
1407 | 1439 | @cacheable |
1408 | 1440 | def composite(f: Callable[..., Ex]) -> Callable[..., SearchStrategy[Ex]]: |
1409 | 1441 | """Defines a strategy that is built out of potentially arbitrarily many |
|
0 commit comments