Skip to content

Commit fb91f66

Browse files
committed
Use py39 type annotations
1 parent 60b1316 commit fb91f66

File tree

12 files changed

+91
-109
lines changed

12 files changed

+91
-109
lines changed

hypothesis-python/src/hypothesis/core.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,19 +24,15 @@
2424
import warnings
2525
import zlib
2626
from collections import defaultdict
27+
from collections.abc import Coroutine, Hashable
2728
from functools import partial
2829
from random import Random
2930
from typing import (
3031
TYPE_CHECKING,
3132
Any,
3233
BinaryIO,
3334
Callable,
34-
Coroutine,
35-
Hashable,
36-
List,
3735
Optional,
38-
Tuple,
39-
Type,
4036
TypeVar,
4137
Union,
4238
overload,
@@ -179,7 +175,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
179175
if not (args or kwargs):
180176
raise InvalidArgument("An example must provide at least one argument")
181177

182-
self.hypothesis_explicit_examples: List[Example] = []
178+
self.hypothesis_explicit_examples: list[Example] = []
183179
self._this_example = Example(tuple(args), kwargs)
184180

185181
def __call__(self, test: TestFunc) -> TestFunc:
@@ -194,7 +190,7 @@ def xfail(
194190
*,
195191
reason: str = "",
196192
raises: Union[
197-
Type[BaseException], Tuple[Type[BaseException], ...]
193+
type[BaseException], tuple[type[BaseException], ...]
198194
] = BaseException,
199195
) -> "example":
200196
"""Mark this example as an expected failure, similarly to
@@ -1825,7 +1821,7 @@ def find(
18251821
)
18261822
specifier.validate()
18271823

1828-
last: List[Ex] = []
1824+
last: list[Ex] = []
18291825

18301826
@settings
18311827
@given(specifier)

hypothesis-python/src/hypothesis/extra/ghostwriter.py

Lines changed: 27 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@
8282
import types
8383
import warnings
8484
from collections import OrderedDict, defaultdict
85+
from collections.abc import Iterable, Mapping
8586
from itertools import permutations, zip_longest
8687
from keyword import iskeyword as _iskeyword
8788
from string import ascii_lowercase
@@ -91,16 +92,9 @@
9192
Any,
9293
Callable,
9394
DefaultDict,
94-
Dict,
9595
ForwardRef,
96-
Iterable,
97-
List,
98-
Mapping,
9996
NamedTuple,
10097
Optional,
101-
Set,
102-
Tuple,
103-
Type,
10498
TypeVar,
10599
Union,
106100
get_args,
@@ -156,8 +150,8 @@ def test_{test_kind}_{func_name}({arg_names}){return_annotation}:
156150
reject()
157151
""".strip()
158152

159-
Except = Union[Type[Exception], Tuple[Type[Exception], ...]]
160-
ImportSet = Set[Union[str, Tuple[str, str]]]
153+
Except = Union[type[Exception], tuple[type[Exception], ...]]
154+
ImportSet = set[Union[str, tuple[str, str]]]
161155
_quietly_settings = settings(
162156
database=None,
163157
deadline=None,
@@ -166,7 +160,7 @@ def test_{test_kind}_{func_name}({arg_names}){return_annotation}:
166160
)
167161

168162

169-
def _dedupe_exceptions(exc: Tuple[Type[Exception], ...]) -> Tuple[Type[Exception], ...]:
163+
def _dedupe_exceptions(exc: tuple[type[Exception], ...]) -> tuple[type[Exception], ...]:
170164
# This is reminiscent of de-duplication logic I wrote for flake8-bugbear,
171165
# but with access to the actual objects we can just check for subclasses.
172166
# This lets us print e.g. `Exception` instead of `(Exception, OSError)`.
@@ -177,7 +171,7 @@ def _dedupe_exceptions(exc: Tuple[Type[Exception], ...]) -> Tuple[Type[Exception
177171
return tuple(sorted(uniques, key=lambda e: e.__name__))
178172

179173

180-
def _check_except(except_: Except) -> Tuple[Type[Exception], ...]:
174+
def _check_except(except_: Except) -> tuple[type[Exception], ...]:
181175
if isinstance(except_, tuple):
182176
for i, e in enumerate(except_):
183177
if not isinstance(e, type) or not issubclass(e, Exception):
@@ -194,7 +188,7 @@ def _check_except(except_: Except) -> Tuple[Type[Exception], ...]:
194188
return (except_,)
195189

196190

197-
def _exception_string(except_: Tuple[Type[Exception], ...]) -> Tuple[ImportSet, str]:
191+
def _exception_string(except_: tuple[type[Exception], ...]) -> tuple[ImportSet, str]:
198192
if not except_:
199193
return set(), ""
200194
exceptions = []
@@ -215,7 +209,7 @@ def _check_style(style: str) -> None:
215209
raise InvalidArgument(f"Valid styles are 'pytest' or 'unittest', got {style!r}")
216210

217211

218-
def _exceptions_from_docstring(doc: str) -> Tuple[Type[Exception], ...]:
212+
def _exceptions_from_docstring(doc: str) -> tuple[type[Exception], ...]:
219213
"""Return a tuple of exceptions that the docstring says may be raised.
220214
221215
Note that we ignore non-builtin exception types for simplicity, as this is
@@ -250,7 +244,7 @@ def _type_from_doc_fragment(token: str) -> Optional[type]:
250244
if elems is None and elem_token.endswith("s"):
251245
elems = _type_from_doc_fragment(elem_token[:-1])
252246
if elems is not None and coll_token in ("list", "sequence", "collection"):
253-
return List[elems] # type: ignore
247+
return list[elems] # type: ignore
254248
# This might be e.g. "array-like of float"; arrays is better than nothing
255249
# even if we can't conveniently pass a generic type around.
256250
return _type_from_doc_fragment(coll_token)
@@ -451,7 +445,7 @@ def _guess_strategy_by_argname(name: str) -> st.SearchStrategy:
451445
return st.nothing()
452446

453447

454-
def _get_params_builtin_fn(func: Callable) -> List[inspect.Parameter]:
448+
def _get_params_builtin_fn(func: Callable) -> list[inspect.Parameter]:
455449
if (
456450
isinstance(func, (types.BuiltinFunctionType, types.BuiltinMethodType))
457451
and hasattr(func, "__doc__")
@@ -483,7 +477,7 @@ def _get_params_builtin_fn(func: Callable) -> List[inspect.Parameter]:
483477
return []
484478

485479

486-
def _get_params_ufunc(func: Callable) -> List[inspect.Parameter]:
480+
def _get_params_ufunc(func: Callable) -> list[inspect.Parameter]:
487481
if _is_probably_ufunc(func):
488482
# `inspect.signature` results vary for ufunc objects, but we can work out
489483
# what the required parameters would look like if it was reliable.
@@ -498,7 +492,7 @@ def _get_params_ufunc(func: Callable) -> List[inspect.Parameter]:
498492
return []
499493

500494

501-
def _get_params(func: Callable) -> Dict[str, inspect.Parameter]:
495+
def _get_params(func: Callable) -> dict[str, inspect.Parameter]:
502496
"""Get non-vararg parameters of `func` as an ordered dict."""
503497
try:
504498
params = list(get_signature(func).parameters.values())
@@ -522,7 +516,7 @@ def _get_params(func: Callable) -> Dict[str, inspect.Parameter]:
522516

523517
def _params_to_dict(
524518
params: Iterable[inspect.Parameter],
525-
) -> Dict[str, inspect.Parameter]:
519+
) -> dict[str, inspect.Parameter]:
526520
var_param_kinds = (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD)
527521
return OrderedDict((p.name, p) for p in params if p.kind not in var_param_kinds)
528522

@@ -548,7 +542,7 @@ def _with_any_registered():
548542

549543
def _get_strategies(
550544
*funcs: Callable, pass_result_to_next_func: bool = False
551-
) -> Dict[str, st.SearchStrategy]:
545+
) -> dict[str, st.SearchStrategy]:
552546
"""Return a dict of strategies for the union of arguments to `funcs`.
553547
554548
If `pass_result_to_next_func` is True, assume that the result of each function
@@ -558,7 +552,7 @@ def _get_strategies(
558552
This dict is used to construct our call to the `@given(...)` decorator.
559553
"""
560554
assert funcs, "Must pass at least one function"
561-
given_strategies: Dict[str, st.SearchStrategy] = {}
555+
given_strategies: dict[str, st.SearchStrategy] = {}
562556
for i, f in enumerate(funcs):
563557
params = _get_params(f)
564558
if pass_result_to_next_func and i >= 1:
@@ -735,7 +729,7 @@ def _valid_syntax_repr(strategy):
735729

736730
# When we ghostwrite for a module, we want to treat that as the __module__ for
737731
# each function, rather than whichever internal file it was actually defined in.
738-
KNOWN_FUNCTION_LOCATIONS: Dict[object, str] = {}
732+
KNOWN_FUNCTION_LOCATIONS: dict[object, str] = {}
739733

740734

741735
def _get_module_helper(obj):
@@ -832,13 +826,13 @@ def _make_test_body(
832826
*funcs: Callable,
833827
ghost: str,
834828
test_body: str,
835-
except_: Tuple[Type[Exception], ...],
829+
except_: tuple[type[Exception], ...],
836830
assertions: str = "",
837831
style: str,
838832
given_strategies: Optional[Mapping[str, Union[str, st.SearchStrategy]]] = None,
839833
imports: Optional[ImportSet] = None,
840834
annotate: bool,
841-
) -> Tuple[ImportSet, str]:
835+
) -> tuple[ImportSet, str]:
842836
# A set of modules to import - we might add to this later. The import code
843837
# is written later, so we can have one import section for multiple magic()
844838
# test functions.
@@ -899,7 +893,7 @@ def _make_test_body(
899893
def _annotate_args(
900894
argnames: Iterable[str], funcs: Iterable[Callable], imports: ImportSet
901895
) -> Iterable[str]:
902-
arg_parameters: DefaultDict[str, Set[Any]] = defaultdict(set)
896+
arg_parameters: DefaultDict[str, set[Any]] = defaultdict(set)
903897
for func in funcs:
904898
try:
905899
params = tuple(get_signature(func, eval_str=True).parameters.values())
@@ -922,7 +916,7 @@ def _annotate_args(
922916

923917
class _AnnotationData(NamedTuple):
924918
type_name: str
925-
imports: Set[str]
919+
imports: set[str]
926920

927921

928922
def _parameters_to_annotation_name(
@@ -949,7 +943,7 @@ def _parameters_to_annotation_name(
949943

950944

951945
def _join_generics(
952-
origin_type_data: Optional[Tuple[str, Set[str]]],
946+
origin_type_data: Optional[tuple[str, set[str]]],
953947
annotations: Iterable[Optional[_AnnotationData]],
954948
) -> Optional[_AnnotationData]:
955949
if origin_type_data is None:
@@ -976,9 +970,9 @@ def _join_generics(
976970

977971
def _join_argument_annotations(
978972
annotations: Iterable[Optional[_AnnotationData]],
979-
) -> Optional[Tuple[List[str], Set[str]]]:
980-
imports: Set[str] = set()
981-
arg_types: List[str] = []
973+
) -> Optional[tuple[list[str], set[str]]]:
974+
imports: set[str] = set()
975+
arg_types: list[str] = []
982976

983977
for annotation in annotations:
984978
if annotation is None:
@@ -1134,10 +1128,10 @@ def _is_probably_ufunc(obj):
11341128
)
11351129

11361130

1137-
def _get_testable_functions(thing: object) -> Dict[str, Callable]:
1131+
def _get_testable_functions(thing: object) -> dict[str, Callable]:
11381132
by_name = {}
11391133
if callable(thing):
1140-
funcs: List[Optional[Any]] = [thing]
1134+
funcs: list[Optional[Any]] = [thing]
11411135
elif isinstance(thing, types.ModuleType):
11421136
if hasattr(thing, "__all__"):
11431137
funcs = [getattr(thing, name, None) for name in thing.__all__]
@@ -1732,10 +1726,10 @@ def _make_binop_body(
17321726
commutative: bool = True,
17331727
identity: Union[X, EllipsisType, None] = ...,
17341728
distributes_over: Optional[Callable[[X, X], X]] = None,
1735-
except_: Tuple[Type[Exception], ...],
1729+
except_: tuple[type[Exception], ...],
17361730
style: str,
17371731
annotate: bool,
1738-
) -> Tuple[ImportSet, str]:
1732+
) -> tuple[ImportSet, str]:
17391733
strategies = _get_strategies(func)
17401734
operands, b = (strategies.pop(p) for p in list(_get_params(func))[:2])
17411735
if repr(operands) != repr(b):

hypothesis-python/src/hypothesis/internal/compat.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
import sysconfig
1818
import typing
1919
from functools import partial
20-
from typing import Any, ForwardRef, List, Optional, TypedDict as TypedDict, get_args
20+
from typing import Any, ForwardRef, Optional, TypedDict as TypedDict, get_args
2121

2222
try:
2323
BaseExceptionGroup = BaseExceptionGroup
@@ -218,7 +218,7 @@ def ceil(x):
218218
return y
219219

220220

221-
def extract_bits(x: int, /, width: Optional[int] = None) -> List[int]:
221+
def extract_bits(x: int, /, width: Optional[int] = None) -> list[int]:
222222
assert x >= 0
223223
result = []
224224
while x:

0 commit comments

Comments
 (0)