Skip to content

Commit

Permalink
Document functions() inference
Browse files Browse the repository at this point in the history
Fixes issue 3217.
  • Loading branch information
Zac-HD committed Jan 31, 2022
1 parent 4d9cb32 commit 57e94e7
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
11 changes: 7 additions & 4 deletions hypothesis-python/src/hypothesis/strategies/_internal/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1841,19 +1841,20 @@ def emails() -> SearchStrategy[str]:
def functions(
*,
like: Callable[..., Any] = lambda: None,
returns: Optional[SearchStrategy[Any]] = None,
returns: Union[SearchStrategy[Any], InferType] = infer,
pure: bool = False,
) -> SearchStrategy[Callable[..., Any]]:
# The proper type signature of `functions()` would have T instead of Any, but mypy
# disallows default args for generics: https://github.com/python/mypy/issues/3737
"""functions(*, like=lambda: None, returns=none(), pure=False)
"""functions(*, like=lambda: None, returns=infer, pure=False)
A strategy for functions, which can be used in callbacks.
The generated functions will mimic the interface of ``like``, which must
be a callable (including a class, method, or function). The return value
for the function is drawn from the ``returns`` argument, which must be a
strategy.
strategy. If ``returns`` is not passed, we attempt to infer a strategy
from the return-type annotation if present, falling back to :func:`~none`.
If ``pure=True``, all arguments passed to the generated function must be
hashable, and if passed identical arguments the original return value will
Expand All @@ -1872,7 +1873,9 @@ def functions(
f"but got non-callable like={nicerepr(like)!r}"
)

if returns is None:
if returns is None or returns is infer:
# Passing `None` has never been *documented* as working, but it still
# did from May 2020 to Jan 2022 so we'll avoid breaking it without cause.
hints = get_type_hints(like)
returns = from_type(hints.get("return", type(None)))

Expand Down
4 changes: 2 additions & 2 deletions hypothesis-python/tests/cover/test_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

import pytest

from hypothesis import assume, given
from hypothesis import assume, given, infer
from hypothesis.errors import InvalidArgument, InvalidState
from hypothesis.strategies import booleans, functions, integers

Expand Down Expand Up @@ -112,7 +112,7 @@ def test_can_call_default_like_arg():
# branch for calling it otherwise and alternative workarounds are worse.
defaults = getfullargspec(functions).kwonlydefaults
assert defaults["like"]() is None
assert defaults["returns"] is None
assert defaults["returns"] is infer


def func(arg, *, kwonly_arg):
Expand Down

0 comments on commit 57e94e7

Please sign in to comment.