Skip to content

Commit

Permalink
remaining typing upgrades
Browse files Browse the repository at this point in the history
  • Loading branch information
Zac-HD committed Oct 10, 2024
1 parent d7f6538 commit f4d66f4
Show file tree
Hide file tree
Showing 51 changed files with 251 additions and 375 deletions.
3 changes: 3 additions & 0 deletions hypothesis-python/RELEASE.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
RELEASE_TYPE: patch

This patch upgrades remaining type annotations to Python 3.9 syntax.
6 changes: 3 additions & 3 deletions hypothesis-python/src/_hypothesis_ftz_detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@

import importlib
import sys
from typing import TYPE_CHECKING, Callable, Optional, Set, Tuple
from typing import TYPE_CHECKING, Callable, Optional

if TYPE_CHECKING:
from multiprocessing import Queue
from typing import TypeAlias

FTZCulprits: "TypeAlias" = Tuple[Optional[bool], Set[str]]
FTZCulprits: "TypeAlias" = tuple[Optional[bool], set[str]]


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

Expand Down
19 changes: 5 additions & 14 deletions hypothesis-python/src/hypothesis/_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,9 @@
import inspect
import os
import warnings
from collections.abc import Collection
from enum import Enum, EnumMeta, IntEnum, unique
from typing import (
TYPE_CHECKING,
Any,
ClassVar,
Collection,
Dict,
List,
Optional,
TypeVar,
Union,
)
from typing import TYPE_CHECKING, Any, ClassVar, Optional, TypeVar, Union

import attr

Expand All @@ -49,7 +40,7 @@

__all__ = ["settings"]

all_settings: Dict[str, "Setting"] = {}
all_settings: dict[str, "Setting"] = {}

T = TypeVar("T")

Expand Down Expand Up @@ -138,7 +129,7 @@ class settings(metaclass=settingsMeta):
"""

__definitions_are_locked = False
_profiles: ClassVar[Dict[str, "settings"]] = {}
_profiles: ClassVar[dict[str, "settings"]] = {}
__module__ = "hypothesis"

def __getattr__(self, name):
Expand Down Expand Up @@ -479,7 +470,7 @@ def __repr__(self):
return f"{self.__class__.__name__}.{self.name}"

@classmethod
def all(cls) -> List["HealthCheck"]:
def all(cls) -> list["HealthCheck"]:
# Skipping of deprecated attributes is handled in HealthCheckMeta.__iter__
note_deprecation(
"`HealthCheck.all()` is deprecated; use `list(HealthCheck)` instead.",
Expand Down
7 changes: 4 additions & 3 deletions hypothesis-python/src/hypothesis/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@
import os
import sys
import warnings
from collections.abc import Iterable
from datetime import datetime, timedelta, timezone
from functools import lru_cache
from hashlib import sha384
from os import getenv
from pathlib import Path, PurePath
from typing import Dict, Iterable, Optional, Set
from typing import Optional
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
from zipfile import BadZipFile, ZipFile
Expand Down Expand Up @@ -195,7 +196,7 @@ class DirectoryBasedExampleDatabase(ExampleDatabase):

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

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

# Message to display if user doesn't wrap around ReadOnlyDatabase
self._read_only_message = (
Expand Down
12 changes: 6 additions & 6 deletions hypothesis-python/src/hypothesis/extra/_array_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
# obtain one at https://mozilla.org/MPL/2.0/.

import re
from typing import NamedTuple, Optional, Tuple, Union
from typing import NamedTuple, Optional, Union

from hypothesis import assume, strategies as st
from hypothesis.errors import InvalidArgument
Expand All @@ -36,13 +36,13 @@
]


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


class BroadcastableShapes(NamedTuple):
input_shapes: Tuple[Shape, ...]
input_shapes: tuple[Shape, ...]
result_shape: Shape


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


class _GUfuncSig(NamedTuple):
input_shapes: Tuple[Shape, ...]
input_shapes: tuple[Shape, ...]
result_shape: Shape


Expand Down
18 changes: 6 additions & 12 deletions hypothesis-python/src/hypothesis/extra/array_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,15 @@

import math
import sys
from collections.abc import Iterable, Iterator, Mapping, Sequence
from numbers import Real
from types import SimpleNamespace
from typing import (
TYPE_CHECKING,
Any,
Iterable,
Iterator,
List,
Literal,
Mapping,
NamedTuple,
Optional,
Sequence,
Tuple,
Type,
TypeVar,
Union,
get_args,
Expand Down Expand Up @@ -89,7 +83,7 @@


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

def partition_attributes_and_stubs(
xp: Any, attributes: Iterable[str]
) -> Tuple[List[Any], List[str]]:
) -> tuple[list[Any], list[str]]:
non_stubs = []
stubs = []
for attr in attributes:
Expand All @@ -112,7 +106,7 @@ def partition_attributes_and_stubs(
return non_stubs, stubs


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

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


@check_function
def check_dtypes(xp: Any, dtypes: List[DataType], stubs: List[str]) -> None:
def check_dtypes(xp: Any, dtypes: list[DataType], stubs: list[str]) -> None:
if len(dtypes) == 0:
assert len(stubs) > 0, "No dtypes passed but stubs is empty"
f_stubs = ", ".join(stubs)
Expand Down
4 changes: 2 additions & 2 deletions hypothesis-python/src/hypothesis/extra/codemods.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
import functools
import importlib
from inspect import Parameter, signature
from typing import ClassVar, List
from typing import ClassVar

import libcst as cst
import libcst.matchers as m
Expand All @@ -65,7 +65,7 @@ def refactor(code: str) -> str:
"""
context = cst.codemod.CodemodContext()
mod = cst.parse_module(code)
transforms: List[VisitorBasedCodemodCommand] = [
transforms: list[VisitorBasedCodemodCommand] = [
HypothesisFixPositionalKeywonlyArgs(context),
HypothesisFixComplexMinMagnitude(context),
HypothesisFixHealthCheckAll(context),
Expand Down
8 changes: 4 additions & 4 deletions hypothesis-python/src/hypothesis/extra/django/_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from datetime import datetime, timedelta
from decimal import Decimal
from functools import lru_cache
from typing import Any, Callable, Dict, Type, TypeVar, Union
from typing import Any, Callable, TypeVar, Union

import django
from django import forms as df
Expand Down Expand Up @@ -68,8 +68,8 @@ def timezones():


# Mapping of field types, to strategy objects or functions of (type) -> strategy
_FieldLookUpType = Dict[
Type[AnyField],
_FieldLookUpType = dict[
type[AnyField],
Union[st.SearchStrategy, Callable[[Any], st.SearchStrategy]],
]
_global_field_lookup: _FieldLookUpType = {
Expand Down Expand Up @@ -319,7 +319,7 @@ def _for_model_multiple_choice(field):


def register_field_strategy(
field_type: Type[AnyField], strategy: st.SearchStrategy
field_type: type[AnyField], strategy: st.SearchStrategy
) -> None:
"""Add an entry to the global field-to-strategy lookup used by
:func:`~hypothesis.extra.django.from_field`.
Expand Down
6 changes: 3 additions & 3 deletions hypothesis-python/src/hypothesis/extra/django/_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import sys
import unittest
from functools import partial
from typing import TYPE_CHECKING, Optional, Type, TypeVar, Union
from typing import TYPE_CHECKING, Optional, TypeVar, Union

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

@defines_strategy()
def from_model(
model: Type[ModelT], /, **field_strategies: Union[st.SearchStrategy, EllipsisType]
model: type[ModelT], /, **field_strategies: Union[st.SearchStrategy, EllipsisType]
) -> st.SearchStrategy[ModelT]:
"""Return a strategy for examples of ``model``.
Expand Down Expand Up @@ -136,7 +136,7 @@ def _models_impl(draw, strat):

@defines_strategy()
def from_form(
form: Type[df.Form],
form: type[df.Form],
form_kwargs: Optional[dict] = None,
**field_strategies: Union[st.SearchStrategy, EllipsisType],
) -> st.SearchStrategy[df.Form]:
Expand Down
4 changes: 2 additions & 2 deletions hypothesis-python/src/hypothesis/extra/lark.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"""

from inspect import signature
from typing import Dict, Optional
from typing import Optional

import lark
from lark.grammar import NonTerminal, Terminal
Expand Down Expand Up @@ -201,7 +201,7 @@ def from_lark(
grammar: lark.lark.Lark,
*,
start: Optional[str] = None,
explicit: Optional[Dict[str, st.SearchStrategy[str]]] = None,
explicit: Optional[dict[str, st.SearchStrategy[str]]] = None,
alphabet: st.SearchStrategy[str] = st.characters(codec="utf-8"),
) -> st.SearchStrategy[str]:
"""A strategy for strings accepted by the given context-free grammar.
Expand Down
24 changes: 6 additions & 18 deletions hypothesis-python/src/hypothesis/extra/numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,8 @@
import importlib
import math
import types
from typing import (
TYPE_CHECKING,
Any,
Literal,
Mapping,
Optional,
Sequence,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
)
from collections.abc import Mapping, Sequence
from typing import TYPE_CHECKING, Any, Literal, Optional, TypeVar, Union, cast, overload

import numpy as np

Expand Down Expand Up @@ -1190,7 +1178,7 @@ def integer_array_indices(
shape: Shape,
*,
result_shape: st.SearchStrategy[Shape] = array_shapes(),
) -> "st.SearchStrategy[Tuple[NDArray[np.signedinteger[Any]], ...]]": ...
) -> "st.SearchStrategy[tuple[NDArray[np.signedinteger[Any]], ...]]": ...


@overload
Expand All @@ -1200,7 +1188,7 @@ def integer_array_indices(
*,
result_shape: st.SearchStrategy[Shape] = array_shapes(),
dtype: "np.dtype[I]",
) -> "st.SearchStrategy[Tuple[NDArray[I], ...]]": ...
) -> "st.SearchStrategy[tuple[NDArray[I], ...]]": ...


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


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

0 comments on commit f4d66f4

Please sign in to comment.