Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Annotate decorators with ParamSpec #3212

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions hypothesis-python/RELEASE.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
RELEASE_TYPE: minor
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wasn't sure whether to consider this minor or patch. On one hand, it only touches annotations and has no effect at runtime, so should probably be considered patch. However, if anyone is running mypy on their code which uses Hypothesis, the increased strictness of the annotations could cause mypy to fail code that passed before, which could be considered a breaking change?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's honestly a borderline case, but in borderline cases I prefer to err on the side of minor - we make no compatibility guarantees about type annotations, but it's still polite to make version constraints easy if we think users might want them.


This preserves the type annotations of functions passed to :func:`hypothesis.strategies.composite` and :func:`hypothesis.strategies.functions` by using :obj:`python:typing.ParamSpec`.

This improves the ability of static type-checkers to check test code that uses Hypothesis, and improves auto-completion in IDEs.
4 changes: 1 addition & 3 deletions hypothesis-python/src/hypothesis/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -951,9 +951,7 @@ def fuzz_one_input(
def given(
*_given_arguments: Union[SearchStrategy, InferType],
**_given_kwargs: Union[SearchStrategy, InferType],
) -> Callable[
[Callable[..., Union[None, Coroutine[Any, Any, None]]]], Callable[..., None]
]:
) -> Callable[[Callable[..., Union[None, Coroutine[Any, Any, None]]]], Callable[..., None]]:
"""A decorator for turning a test function that accepts arguments into a
randomized test.

Expand Down
12 changes: 8 additions & 4 deletions hypothesis-python/src/hypothesis/strategies/_internal/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
from uuid import UUID

import attr
from typing_extensions import Concatenate
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think typing_extensions is a requirement of Hypothesis, and I'm not sure if you want to make it one. Any ideas how to handle this? Anything I could reuse from strategies/_internal/types.py?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not a requirement, and I'd like to keep it optional - in which case I think the best option is to try importing ParamSpec (from typing, then typing_extensions); and then have two function definitions behind an if ParamSpec is not None:/else condition. Probably makes sense to write this as a very simple wrapper for an unannoted _-prefixed function so we're at least not duplicating the logic.


from hypothesis.control import cleanup, note
from hypothesis.errors import InvalidArgument, ResolutionFailed
Expand Down Expand Up @@ -94,6 +95,7 @@
from hypothesis.strategies._internal.shared import SharedStrategy
from hypothesis.strategies._internal.strategies import (
Ex,
P,
SampledFromStrategy,
T,
one_of,
Expand Down Expand Up @@ -1451,7 +1453,9 @@ def __call__(self, strategy: SearchStrategy[Ex], label: object = None) -> Ex:


@cacheable
def composite(f: Callable[..., Ex]) -> Callable[..., SearchStrategy[Ex]]:
def composite(
f: Callable[Concatenate[DrawFn, P], Ex]
) -> Callable[P, SearchStrategy[Ex]]:
"""Defines a strategy that is built out of potentially arbitrarily many
other strategies.

Expand Down Expand Up @@ -1850,10 +1854,10 @@ def emails() -> SearchStrategy[str]:
@defines_strategy()
def functions(
*,
like: Callable[..., Any] = lambda: None,
returns: Optional[SearchStrategy[Any]] = None,
like: Callable[P, T] = lambda: None,
returns: Optional[SearchStrategy[T]] = None,
pure: bool = False,
) -> SearchStrategy[Callable[..., Any]]:
) -> SearchStrategy[Callable[P, T]]:
# 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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
overload,
)

from typing_extensions import ParamSpec

from hypothesis._settings import HealthCheck, Phase, Verbosity, settings
from hypothesis.control import _current_build_context, assume
from hypothesis.errors import (
Expand Down Expand Up @@ -54,6 +56,7 @@
T3 = TypeVar("T3")
T4 = TypeVar("T4")
T5 = TypeVar("T5")
P = ParamSpec("P")

calculating = UniqueIdentifier("calculating")

Expand Down
26 changes: 26 additions & 0 deletions whole-repo-tests/test_type_hints.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,32 @@ def test_drawfn_type_tracing(tmpdir):
assert got == "str"


def test_composite_type_tracing(tmpdir):
f = tmpdir.join("check_mypy_on_st_composite.py")
f.write(
"from hypothesis.strategies import composite, DrawFn\n"
"@composite\n"
"def comp(draw: DrawFn, x: int) -> int:\n"
" return x\n"
"reveal_type(comp)\n"
)
got = get_mypy_analysed_type(str(f.realpath()), ...)
assert got == "def (x: int) -> int"


def test_functions_type_tracing(tmpdir):
f = tmpdir.join("check_mypy_on_st_functions.py")
f.write(
"from hypothesis.strategies import functions\n"
"def like(x: int, y: str) -> str:\n"
" return str(x) + y\n"
"st = functions(like)\n"
"reveal_type(st)\n"
)
got = get_mypy_analysed_type(str(f.realpath()), ...)
assert got == "SearchStrategy[Callable[[int, str], str]]"


def test_settings_preserves_type(tmpdir):
f = tmpdir.join("check_mypy_on_settings.py")
f.write(
Expand Down