Skip to content

Commit bf52675

Browse files
authored
Merge pull request #4135 from Zac-HD/py39-type-hints
Further typing upgrades for Python 3.9
2 parents ccdbfea + f4d66f4 commit bf52675

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+253
-376
lines changed

hypothesis-python/RELEASE.rst

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
RELEASE_TYPE: patch
2+
3+
This patch upgrades remaining type annotations to Python 3.9 syntax.

hypothesis-python/setup.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def local_file(name):
6060
"pytest": ["pytest>=4.6"],
6161
"dpcontracts": ["dpcontracts>=0.4"],
6262
"redis": ["redis>=3.0.0"],
63-
"crosshair": ["hypothesis-crosshair>=0.0.14", "crosshair-tool>=0.0.73"],
63+
"crosshair": ["hypothesis-crosshair>=0.0.16", "crosshair-tool>=0.0.74"],
6464
# zoneinfo is an odd one: every dependency is platform-conditional.
6565
"zoneinfo": [
6666
"tzdata>=2024.2 ; sys_platform == 'win32' or sys_platform == 'emscripten'",

hypothesis-python/src/_hypothesis_ftz_detector.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,13 @@
1818

1919
import importlib
2020
import sys
21-
from typing import TYPE_CHECKING, Callable, Optional, Set, Tuple
21+
from typing import TYPE_CHECKING, Callable, Optional
2222

2323
if TYPE_CHECKING:
2424
from multiprocessing import Queue
2525
from typing import TypeAlias
2626

27-
FTZCulprits: "TypeAlias" = Tuple[Optional[bool], Set[str]]
27+
FTZCulprits: "TypeAlias" = tuple[Optional[bool], set[str]]
2828

2929

3030
KNOWN_EVER_CULPRITS = (
@@ -104,7 +104,7 @@ def identify_ftz_culprits() -> str:
104104
# that importing them in a new process sets the FTZ state. As a heuristic, we'll
105105
# start with packages known to have ever enabled FTZ, then top-level packages as
106106
# a way to eliminate large fractions of the search space relatively quickly.
107-
def key(name: str) -> Tuple[bool, int, str]:
107+
def key(name: str) -> tuple[bool, int, str]:
108108
"""Prefer known-FTZ modules, then top-level packages, then alphabetical."""
109109
return (name not in KNOWN_EVER_CULPRITS, name.count("."), name)
110110

hypothesis-python/src/hypothesis/_settings.py

+5-14
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,9 @@
1919
import inspect
2020
import os
2121
import warnings
22+
from collections.abc import Collection
2223
from enum import Enum, EnumMeta, IntEnum, unique
23-
from typing import (
24-
TYPE_CHECKING,
25-
Any,
26-
ClassVar,
27-
Collection,
28-
Dict,
29-
List,
30-
Optional,
31-
TypeVar,
32-
Union,
33-
)
24+
from typing import TYPE_CHECKING, Any, ClassVar, Optional, TypeVar, Union
3425

3526
import attr
3627

@@ -49,7 +40,7 @@
4940

5041
__all__ = ["settings"]
5142

52-
all_settings: Dict[str, "Setting"] = {}
43+
all_settings: dict[str, "Setting"] = {}
5344

5445
T = TypeVar("T")
5546

@@ -138,7 +129,7 @@ class settings(metaclass=settingsMeta):
138129
"""
139130

140131
__definitions_are_locked = False
141-
_profiles: ClassVar[Dict[str, "settings"]] = {}
132+
_profiles: ClassVar[dict[str, "settings"]] = {}
142133
__module__ = "hypothesis"
143134

144135
def __getattr__(self, name):
@@ -479,7 +470,7 @@ def __repr__(self):
479470
return f"{self.__class__.__name__}.{self.name}"
480471

481472
@classmethod
482-
def all(cls) -> List["HealthCheck"]:
473+
def all(cls) -> list["HealthCheck"]:
483474
# Skipping of deprecated attributes is handled in HealthCheckMeta.__iter__
484475
note_deprecation(
485476
"`HealthCheck.all()` is deprecated; use `list(HealthCheck)` instead.",

hypothesis-python/src/hypothesis/database.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,13 @@
1414
import os
1515
import sys
1616
import warnings
17+
from collections.abc import Iterable
1718
from datetime import datetime, timedelta, timezone
1819
from functools import lru_cache
1920
from hashlib import sha384
2021
from os import getenv
2122
from pathlib import Path, PurePath
22-
from typing import Dict, Iterable, Optional, Set
23+
from typing import Optional
2324
from urllib.error import HTTPError, URLError
2425
from urllib.request import Request, urlopen
2526
from zipfile import BadZipFile, ZipFile
@@ -195,7 +196,7 @@ class DirectoryBasedExampleDatabase(ExampleDatabase):
195196

196197
def __init__(self, path: os.PathLike) -> None:
197198
self.path = Path(path)
198-
self.keypaths: Dict[bytes, Path] = {}
199+
self.keypaths: dict[bytes, Path] = {}
199200

200201
def __repr__(self) -> str:
201202
return f"DirectoryBasedExampleDatabase({self.path!r})"
@@ -444,7 +445,7 @@ def __init__(
444445
# .hypothesis/github-artifacts/<artifact-name>/<modified_isoformat>.zip
445446
self._artifact: Optional[Path] = None
446447
# This caches the artifact structure
447-
self._access_cache: Optional[Dict[PurePath, Set[PurePath]]] = None
448+
self._access_cache: Optional[dict[PurePath, set[PurePath]]] = None
448449

449450
# Message to display if user doesn't wrap around ReadOnlyDatabase
450451
self._read_only_message = (

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

+6-6
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
# obtain one at https://mozilla.org/MPL/2.0/.
1010

1111
import re
12-
from typing import NamedTuple, Optional, Tuple, Union
12+
from typing import NamedTuple, Optional, Union
1313

1414
from hypothesis import assume, strategies as st
1515
from hypothesis.errors import InvalidArgument
@@ -36,13 +36,13 @@
3636
]
3737

3838

39-
Shape = Tuple[int, ...]
39+
Shape = tuple[int, ...]
4040
# We silence flake8 here because it disagrees with mypy about `ellipsis` (`type(...)`)
41-
BasicIndex = Tuple[Union[int, slice, None, "ellipsis"], ...] # noqa: F821
41+
BasicIndex = tuple[Union[int, slice, None, "ellipsis"], ...] # noqa: F821
4242

4343

4444
class BroadcastableShapes(NamedTuple):
45-
input_shapes: Tuple[Shape, ...]
45+
input_shapes: tuple[Shape, ...]
4646
result_shape: Shape
4747

4848

@@ -121,7 +121,7 @@ def valid_tuple_axes(
121121
*,
122122
min_size: int = 0,
123123
max_size: Optional[int] = None,
124-
) -> st.SearchStrategy[Tuple[int, ...]]:
124+
) -> st.SearchStrategy[tuple[int, ...]]:
125125
"""All tuples will have a length >= ``min_size`` and <= ``max_size``. The default
126126
value for ``max_size`` is ``ndim``.
127127
@@ -282,7 +282,7 @@ def broadcastable_shapes(
282282

283283

284284
class _GUfuncSig(NamedTuple):
285-
input_shapes: Tuple[Shape, ...]
285+
input_shapes: tuple[Shape, ...]
286286
result_shape: Shape
287287

288288

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

+6-12
Original file line numberDiff line numberDiff line change
@@ -10,21 +10,15 @@
1010

1111
import math
1212
import sys
13+
from collections.abc import Iterable, Iterator, Mapping, Sequence
1314
from numbers import Real
1415
from types import SimpleNamespace
1516
from typing import (
1617
TYPE_CHECKING,
1718
Any,
18-
Iterable,
19-
Iterator,
20-
List,
2119
Literal,
22-
Mapping,
2320
NamedTuple,
2421
Optional,
25-
Sequence,
26-
Tuple,
27-
Type,
2822
TypeVar,
2923
Union,
3024
get_args,
@@ -89,7 +83,7 @@
8983

9084

9185
@check_function
92-
def check_xp_attributes(xp: Any, attributes: List[str]) -> None:
86+
def check_xp_attributes(xp: Any, attributes: list[str]) -> None:
9387
missing_attrs = [attr for attr in attributes if not hasattr(xp, attr)]
9488
if len(missing_attrs) > 0:
9589
f_attrs = ", ".join(missing_attrs)
@@ -100,7 +94,7 @@ def check_xp_attributes(xp: Any, attributes: List[str]) -> None:
10094

10195
def partition_attributes_and_stubs(
10296
xp: Any, attributes: Iterable[str]
103-
) -> Tuple[List[Any], List[str]]:
97+
) -> tuple[list[Any], list[str]]:
10498
non_stubs = []
10599
stubs = []
106100
for attr in attributes:
@@ -112,7 +106,7 @@ def partition_attributes_and_stubs(
112106
return non_stubs, stubs
113107

114108

115-
def warn_on_missing_dtypes(xp: Any, stubs: List[str]) -> None:
109+
def warn_on_missing_dtypes(xp: Any, stubs: list[str]) -> None:
116110
f_stubs = ", ".join(stubs)
117111
warn(
118112
f"Array module {xp.__name__} does not have the following "
@@ -124,7 +118,7 @@ def warn_on_missing_dtypes(xp: Any, stubs: List[str]) -> None:
124118

125119
def find_castable_builtin_for_dtype(
126120
xp: Any, api_version: NominalVersion, dtype: DataType
127-
) -> Type[Union[bool, int, float, complex]]:
121+
) -> type[Union[bool, int, float, complex]]:
128122
"""Returns builtin type which can have values that are castable to the given
129123
dtype, according to :xp-ref:`type promotion rules <type_promotion.html>`.
130124
@@ -591,7 +585,7 @@ def _arrays(
591585

592586

593587
@check_function
594-
def check_dtypes(xp: Any, dtypes: List[DataType], stubs: List[str]) -> None:
588+
def check_dtypes(xp: Any, dtypes: list[DataType], stubs: list[str]) -> None:
595589
if len(dtypes) == 0:
596590
assert len(stubs) > 0, "No dtypes passed but stubs is empty"
597591
f_stubs = ", ".join(stubs)

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

+2-2
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
import functools
4949
import importlib
5050
from inspect import Parameter, signature
51-
from typing import ClassVar, List
51+
from typing import ClassVar
5252

5353
import libcst as cst
5454
import libcst.matchers as m
@@ -65,7 +65,7 @@ def refactor(code: str) -> str:
6565
"""
6666
context = cst.codemod.CodemodContext()
6767
mod = cst.parse_module(code)
68-
transforms: List[VisitorBasedCodemodCommand] = [
68+
transforms: list[VisitorBasedCodemodCommand] = [
6969
HypothesisFixPositionalKeywonlyArgs(context),
7070
HypothesisFixComplexMinMagnitude(context),
7171
HypothesisFixHealthCheckAll(context),

hypothesis-python/src/hypothesis/extra/django/_fields.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from datetime import datetime, timedelta
1414
from decimal import Decimal
1515
from functools import lru_cache
16-
from typing import Any, Callable, Dict, Type, TypeVar, Union
16+
from typing import Any, Callable, TypeVar, Union
1717

1818
import django
1919
from django import forms as df
@@ -68,8 +68,8 @@ def timezones():
6868

6969

7070
# Mapping of field types, to strategy objects or functions of (type) -> strategy
71-
_FieldLookUpType = Dict[
72-
Type[AnyField],
71+
_FieldLookUpType = dict[
72+
type[AnyField],
7373
Union[st.SearchStrategy, Callable[[Any], st.SearchStrategy]],
7474
]
7575
_global_field_lookup: _FieldLookUpType = {
@@ -319,7 +319,7 @@ def _for_model_multiple_choice(field):
319319

320320

321321
def register_field_strategy(
322-
field_type: Type[AnyField], strategy: st.SearchStrategy
322+
field_type: type[AnyField], strategy: st.SearchStrategy
323323
) -> None:
324324
"""Add an entry to the global field-to-strategy lookup used by
325325
:func:`~hypothesis.extra.django.from_field`.

hypothesis-python/src/hypothesis/extra/django/_impl.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import sys
1212
import unittest
1313
from functools import partial
14-
from typing import TYPE_CHECKING, Optional, Type, TypeVar, Union
14+
from typing import TYPE_CHECKING, Optional, TypeVar, Union
1515

1616
from django import forms as df, test as dt
1717
from django.contrib.staticfiles import testing as dst
@@ -66,7 +66,7 @@ class StaticLiveServerTestCase(HypothesisTestCase, dst.StaticLiveServerTestCase)
6666

6767
@defines_strategy()
6868
def from_model(
69-
model: Type[ModelT], /, **field_strategies: Union[st.SearchStrategy, EllipsisType]
69+
model: type[ModelT], /, **field_strategies: Union[st.SearchStrategy, EllipsisType]
7070
) -> st.SearchStrategy[ModelT]:
7171
"""Return a strategy for examples of ``model``.
7272
@@ -136,7 +136,7 @@ def _models_impl(draw, strat):
136136

137137
@defines_strategy()
138138
def from_form(
139-
form: Type[df.Form],
139+
form: type[df.Form],
140140
form_kwargs: Optional[dict] = None,
141141
**field_strategies: Union[st.SearchStrategy, EllipsisType],
142142
) -> st.SearchStrategy[df.Form]:

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

+2-2
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
"""
2626

2727
from inspect import signature
28-
from typing import Dict, Optional
28+
from typing import Optional
2929

3030
import lark
3131
from lark.grammar import NonTerminal, Terminal
@@ -201,7 +201,7 @@ def from_lark(
201201
grammar: lark.lark.Lark,
202202
*,
203203
start: Optional[str] = None,
204-
explicit: Optional[Dict[str, st.SearchStrategy[str]]] = None,
204+
explicit: Optional[dict[str, st.SearchStrategy[str]]] = None,
205205
alphabet: st.SearchStrategy[str] = st.characters(codec="utf-8"),
206206
) -> st.SearchStrategy[str]:
207207
"""A strategy for strings accepted by the given context-free grammar.

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

+6-18
Original file line numberDiff line numberDiff line change
@@ -11,20 +11,8 @@
1111
import importlib
1212
import math
1313
import types
14-
from typing import (
15-
TYPE_CHECKING,
16-
Any,
17-
Literal,
18-
Mapping,
19-
Optional,
20-
Sequence,
21-
Tuple,
22-
Type,
23-
TypeVar,
24-
Union,
25-
cast,
26-
overload,
27-
)
14+
from collections.abc import Mapping, Sequence
15+
from typing import TYPE_CHECKING, Any, Literal, Optional, TypeVar, Union, cast, overload
2816

2917
import numpy as np
3018

@@ -1190,7 +1178,7 @@ def integer_array_indices(
11901178
shape: Shape,
11911179
*,
11921180
result_shape: st.SearchStrategy[Shape] = array_shapes(),
1193-
) -> "st.SearchStrategy[Tuple[NDArray[np.signedinteger[Any]], ...]]": ...
1181+
) -> "st.SearchStrategy[tuple[NDArray[np.signedinteger[Any]], ...]]": ...
11941182

11951183

11961184
@overload
@@ -1200,7 +1188,7 @@ def integer_array_indices(
12001188
*,
12011189
result_shape: st.SearchStrategy[Shape] = array_shapes(),
12021190
dtype: "np.dtype[I]",
1203-
) -> "st.SearchStrategy[Tuple[NDArray[I], ...]]": ...
1191+
) -> "st.SearchStrategy[tuple[NDArray[I], ...]]": ...
12041192

12051193

12061194
@defines_strategy()
@@ -1209,7 +1197,7 @@ def integer_array_indices(
12091197
*,
12101198
result_shape: st.SearchStrategy[Shape] = array_shapes(),
12111199
dtype: "np.dtype[I] | np.dtype[np.signedinteger[Any]]" = np.dtype(int),
1212-
) -> "st.SearchStrategy[Tuple[NDArray[I], ...]]":
1200+
) -> "st.SearchStrategy[tuple[NDArray[I], ...]]":
12131201
"""Return a search strategy for tuples of integer-arrays that, when used
12141202
to index into an array of shape ``shape``, given an array whose shape
12151203
was drawn from ``result_shape``.
@@ -1314,7 +1302,7 @@ def _dtype_from_args(args):
13141302
return np.dtype(dtype)
13151303

13161304

1317-
def _from_type(thing: Type[Ex]) -> Optional[st.SearchStrategy[Ex]]:
1305+
def _from_type(thing: type[Ex]) -> Optional[st.SearchStrategy[Ex]]:
13181306
"""Called by st.from_type to try to infer a strategy for thing using numpy.
13191307
13201308
If we can infer a numpy-specific strategy for thing, we return that; otherwise,

0 commit comments

Comments
 (0)