Skip to content

Commit faa5933

Browse files
committed
Use PEP 585 generic types
Part of #109
1 parent 65c9f8f commit faa5933

34 files changed

+199
-200
lines changed

docs/developing/grass.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
# > imports
22
import enum
3+
from collections.abc import Hashable, Sequence
34
from functools import cached_property
4-
from typing import Dict, Hashable, Optional, Sequence, Tuple
5+
from typing import Optional
56

67
import numpy
78
import xarray
@@ -19,7 +20,7 @@ class GrassGridKind(enum.Enum):
1920
fence = 'fence'
2021

2122

22-
GrassIndex = Tuple[GrassGridKind, Sequence[int]]
23+
GrassIndex = tuple[GrassGridKind, Sequence[int]]
2324

2425

2526
class Grass(DimensionConvention[GrassGridKind, GrassIndex]):
@@ -37,14 +38,14 @@ def check_dataset(cls, dataset: xarray.Dataset) -> Optional[int]:
3738
return Specificity.HIGH
3839
return None
3940

40-
def unpack_index(self, index: GrassIndex) -> Tuple[GrassGridKind, Sequence[int]]:
41+
def unpack_index(self, index: GrassIndex) -> tuple[GrassGridKind, Sequence[int]]:
4142
return index[0], list(index[1])
4243

4344
def pack_index(self, grid_kind: GrassGridKind, indices: Sequence[int]) -> GrassIndex:
4445
return (grid_kind, list(indices))
4546

4647
@cached_property
47-
def grid_dimensions(self) -> Dict[GrassGridKind, Sequence[Hashable]]:
48+
def grid_dimensions(self) -> dict[GrassGridKind, Sequence[Hashable]]:
4849
return {
4950
GrassGridKind.field: ['warp', 'weft'],
5051
GrassGridKind.fence: ['post'],

docs/roles.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import re
2-
from typing import Callable, Iterable, List, Tuple, cast
2+
from collections.abc import Iterable
3+
from typing import Callable, cast
34

45
import yaml
56
from docutils import nodes, utils
@@ -30,7 +31,7 @@ def role_fn(
3031
inliner: Inliner,
3132
options: dict = {},
3233
content: list = [],
33-
) -> Tuple[list, list]:
34+
) -> tuple[list, list]:
3435
match = GITHUB_FULL_REF.match(utils.unescape(text))
3536
if match is not None:
3637
repo = match.group('repo')
@@ -83,15 +84,15 @@ def load_citation_file(self) -> dict:
8384
with open(citation_file, 'r') as f:
8485
return cast(dict, yaml.load(f, yaml.Loader))
8586

86-
def run(self) -> List[nodes.Node]:
87+
def run(self) -> list[nodes.Node]:
8788
if self.options['format'] == 'apa':
8889
return self.run_apa()
8990
elif self.options['format'] == 'biblatex':
9091
return self.run_biblatex()
9192
else:
9293
raise ValueError("Unknown format")
9394

94-
def run_apa(self) -> List[nodes.Node]:
95+
def run_apa(self) -> list[nodes.Node]:
9596
citation = self.load_citation_file()
9697
names = self.comma_ampersand_join(map(self.apa_name, citation['authors']))
9798
year = citation['date-released'].year
@@ -118,7 +119,7 @@ def comma_ampersand_join(self, items: Iterable[str]) -> str:
118119
return items[0]
119120
return '{}, & {}'.format(', '.join(items[:-1]), items[-1])
120121

121-
def run_biblatex(self) -> List[nodes.Node]:
122+
def run_biblatex(self) -> list[nodes.Node]:
122123
citation = self.load_citation_file()
123124

124125
year = citation['date-released'].year

scripts/release.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import shlex
77
import subprocess
88
import sys
9-
from typing import List, Optional
9+
from typing import Optional
1010

1111
PROJECT = pathlib.Path(__file__).parent.parent
1212

@@ -29,7 +29,7 @@
2929

3030

3131
def main(
32-
args: Optional[List[str]] = None,
32+
args: Optional[list[str]] = None,
3333
) -> None:
3434
parser = argparse.ArgumentParser()
3535
add_options(parser)

src/emsarray/cli/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import argparse
77
import importlib
88
import pkgutil
9-
from typing import Iterable, Type
9+
from collections.abc import Iterable
1010

1111
import emsarray
1212

@@ -40,7 +40,7 @@ def main(options: argparse.Namespace) -> None:
4040
options.func(options)
4141

4242

43-
def _find_all_commands() -> Iterable[Type[BaseCommand]]:
43+
def _find_all_commands() -> Iterable[type[BaseCommand]]:
4444
for moduleinfo in pkgutil.iter_modules(commands.__path__):
4545
if moduleinfo.name.startswith('_'):
4646
continue

src/emsarray/cli/commands/clip.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import logging
44
import tempfile
55
from pathlib import Path
6-
from typing import ContextManager
76

87
import emsarray
98
from emsarray.cli import BaseCommand
@@ -39,7 +38,7 @@ def add_arguments(self, parser: argparse.ArgumentParser) -> None:
3938
))
4039

4140
def handle(self, options: argparse.Namespace) -> None:
42-
work_context: ContextManager[Pathish]
41+
work_context: contextlib.AbstractContextManager[Pathish]
4342
if options.work_dir:
4443
work_context = contextlib.nullcontext(options.work_dir)
4544
else:

src/emsarray/cli/commands/export_geometry.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import argparse
22
import logging
33
from pathlib import Path
4-
from typing import Callable, Dict
4+
from typing import Callable
55

66
import xarray
77

@@ -13,7 +13,7 @@
1313
logger = logging.getLogger(__name__)
1414

1515
Writer = Callable[[xarray.Dataset, Pathish], None]
16-
format_writers: Dict[str, Writer] = {
16+
format_writers: dict[str, Writer] = {
1717
'geojson': geometry.write_geojson,
1818
'shapefile': geometry.write_shapefile,
1919
'wkt': geometry.write_wkt,

src/emsarray/cli/commands/plot.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import functools
33
import logging
44
from pathlib import Path
5-
from typing import Any, Callable, Dict, List, Optional, Text, TypeVar
5+
from typing import Any, Callable, Optional, TypeVar
66

77
import emsarray
88
from emsarray.cli import BaseCommand, CommandException
@@ -12,7 +12,7 @@
1212
logger = logging.getLogger(__name__)
1313

1414

15-
def key_value(arg: str, value_type: Callable = str) -> Dict[str, T]:
15+
def key_value(arg: str, value_type: Callable = str) -> dict[str, T]:
1616
try:
1717
name, value = arg.split("=", 2)
1818
except ValueError:
@@ -24,11 +24,11 @@ def key_value(arg: str, value_type: Callable = str) -> Dict[str, T]:
2424
class UpdateDict(argparse.Action):
2525
def __init__(
2626
self,
27-
option_strings: List[str],
27+
option_strings: list[str],
2828
dest: str,
2929
*,
3030
value_type: Callable = str,
31-
default: Optional[Dict[str, Any]] = None,
31+
default: Optional[dict[str, Any]] = None,
3232
**kwargs: Any,
3333
):
3434
if default is None:
@@ -42,7 +42,7 @@ def __call__(
4242
parser: argparse.ArgumentParser,
4343
namespace: argparse.Namespace,
4444
values: Any,
45-
option_string: Optional[Text] = None,
45+
option_string: Optional[str] = None,
4646
) -> None:
4747
super().__call__
4848
holder = getattr(namespace, self.dest, {})

src/emsarray/cli/utils.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,10 @@
99
import re
1010
import sys
1111
import textwrap
12+
from collections.abc import Iterator
1213
from functools import wraps
1314
from pathlib import Path
14-
from typing import Callable, Iterator, List, Optional, Protocol
15+
from typing import Callable, Optional, Protocol
1516

1617
from shapely.geometry import box, shape
1718
from shapely.geometry.base import BaseGeometry
@@ -29,7 +30,7 @@
2930
class MainCallable(Protocol):
3031
def __call__(
3132
self,
32-
argv: Optional[List[str]] = None,
33+
argv: Optional[list[str]] = None,
3334
handle_errors: bool = True,
3435
) -> None:
3536
...
@@ -90,7 +91,7 @@ def main(options: argparse.Namespace) -> None:
9091
.. code-block:: python
9192
9293
@nice_console_errors()
93-
def main(argv: Optional[List[str]]) -> None:
94+
def main(argv: Optional[list[str]]) -> None:
9495
parser = argparse.ArgumentParser()
9596
add_verbosity_group(parser)
9697
command_line_flags(parser)
@@ -111,7 +112,7 @@ def decorator(
111112
) -> MainCallable:
112113
@wraps(fn)
113114
def wrapper(
114-
argv: Optional[List[str]] = None,
115+
argv: Optional[list[str]] = None,
115116
handle_errors: bool = True,
116117
) -> None:
117118
parser = argparse.ArgumentParser(

src/emsarray/compat/shapely.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import warnings
2-
from typing import Generic, Iterable, Tuple, TypeVar, Union, cast
2+
from collections.abc import Iterable
3+
from typing import Generic, TypeVar, Union, cast
34

45
import numpy
56
import shapely
@@ -30,7 +31,7 @@ class SpatialIndex(Generic[T]):
3031

3132
def __init__(
3233
self,
33-
items: Union[numpy.ndarray, Iterable[Tuple[BaseGeometry, T]]],
34+
items: Union[numpy.ndarray, Iterable[tuple[BaseGeometry, T]]],
3435
):
3536
self.items = numpy.array(items, dtype=self.dtype)
3637

src/emsarray/conventions/_base.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@
55
import enum
66
import logging
77
import warnings
8+
from collections.abc import Hashable, Iterable, Sequence
89
from functools import cached_property
910
from typing import (
10-
TYPE_CHECKING, Any, Callable, Dict, FrozenSet, Generic, Hashable, Iterable,
11-
List, Optional, Sequence, Tuple, TypeVar, Union, cast
11+
TYPE_CHECKING, Any, Callable, Generic, Optional, TypeVar, Union, cast
1212
)
1313

1414
import numpy
@@ -399,7 +399,7 @@ def get_depth_name(self) -> Hashable:
399399
except IndexError:
400400
raise NoSuchCoordinateError("Could not find depth coordinate in dataset")
401401

402-
def get_all_depth_names(self) -> List[Hashable]:
402+
def get_all_depth_names(self) -> list[Hashable]:
403403
"""Get the names of all depth layers.
404404
Some datasets include both a depth layer centre,
405405
and the depth layer 'edges'.
@@ -595,7 +595,7 @@ def unravel_index(
595595

596596
@property
597597
@abc.abstractmethod
598-
def grid_kinds(self) -> FrozenSet[GridKind]:
598+
def grid_kinds(self) -> frozenset[GridKind]:
599599
"""
600600
All of the :data:`grid kinds <.GridKind>` this dataset includes.
601601
"""
@@ -612,7 +612,7 @@ def default_grid_kind(self) -> GridKind:
612612

613613
@property
614614
@abc.abstractmethod
615-
def grid_size(self) -> Dict[GridKind, int]:
615+
def grid_size(self) -> dict[GridKind, int]:
616616
"""The linear size of each grid kind."""
617617
pass
618618

@@ -662,7 +662,7 @@ def get_grid_kind(self, data_array: xarray.DataArray) -> GridKind:
662662

663663
def get_grid_kind_and_size(
664664
self, data_array: xarray.DataArray,
665-
) -> Tuple[GridKind, int]:
665+
) -> tuple[GridKind, int]:
666666
"""
667667
Determines the relevant index kind and the extent of the linear index space
668668
for this data array.
@@ -885,7 +885,7 @@ def plot_on_figure(
885885
self,
886886
figure: Figure,
887887
scalar: Optional[DataArrayOrName] = None,
888-
vector: Optional[Tuple[DataArrayOrName, DataArrayOrName]] = None,
888+
vector: Optional[tuple[DataArrayOrName, DataArrayOrName]] = None,
889889
title: Optional[str] = None,
890890
**kwargs: Any,
891891
) -> None:
@@ -965,7 +965,7 @@ def animate_on_figure(
965965
self,
966966
figure: Figure,
967967
scalar: Optional[DataArrayOrName] = None,
968-
vector: Optional[Tuple[DataArrayOrName, DataArrayOrName]] = None,
968+
vector: Optional[tuple[DataArrayOrName, DataArrayOrName]] = None,
969969
coordinate: Optional[DataArrayOrName] = None,
970970
title: Optional[Union[str, Callable[[Any], str]]] = None,
971971
**kwargs: Any,
@@ -1187,7 +1187,7 @@ def make_quiver(
11871187
# sometimes preferring to fill them in later,
11881188
# so `u` and `v` are optional.
11891189
# If they are not provided, we set default quiver values of `numpy.nan`.
1190-
values: Union[Tuple[numpy.ndarray, numpy.ndarray], Tuple[float, float]]
1190+
values: Union[tuple[numpy.ndarray, numpy.ndarray], tuple[float, float]]
11911191
values = numpy.nan, numpy.nan
11921192

11931193
if u is not None and v is not None:
@@ -1422,7 +1422,7 @@ def get_index_for_point(
14221422
return None
14231423

14241424
@abc.abstractmethod
1425-
def selector_for_index(self, index: Index) -> Dict[Hashable, int]:
1425+
def selector_for_index(self, index: Index) -> dict[Hashable, int]:
14261426
"""
14271427
Convert a convention native index into a selector
14281428
that can be passed to :meth:`Dataset.isel <xarray.Dataset.isel>`.
@@ -1516,7 +1516,7 @@ def select_point(self, point: Point) -> xarray.Dataset:
15161516
return self.select_index(index.index)
15171517

15181518
@abc.abstractmethod
1519-
def get_all_geometry_names(self) -> List[Hashable]:
1519+
def get_all_geometry_names(self) -> list[Hashable]:
15201520
"""
15211521
Return a list of the names of all geometry variables used by this convention.
15221522
@@ -1742,7 +1742,7 @@ class DimensionConvention(Convention[GridKind, Index]):
17421742

17431743
@property
17441744
@abc.abstractmethod
1745-
def grid_dimensions(self) -> Dict[GridKind, Sequence[Hashable]]:
1745+
def grid_dimensions(self) -> dict[GridKind, Sequence[Hashable]]:
17461746
"""
17471747
The dimensions associated with a particular grid kind.
17481748
@@ -1760,7 +1760,7 @@ def grid_dimensions(self) -> Dict[GridKind, Sequence[Hashable]]:
17601760
pass
17611761

17621762
@property
1763-
def grid_shape(self) -> Dict[GridKind, Sequence[int]]:
1763+
def grid_shape(self) -> dict[GridKind, Sequence[int]]:
17641764
"""
17651765
The :attr:`shape <numpy.ndarray.shape>` of each grid kind.
17661766
@@ -1775,7 +1775,7 @@ def grid_shape(self) -> Dict[GridKind, Sequence[int]]:
17751775
}
17761776

17771777
@property
1778-
def grid_size(self) -> Dict[GridKind, int]:
1778+
def grid_size(self) -> dict[GridKind, int]:
17791779
return {
17801780
grid_kind: int(numpy.prod(shape))
17811781
for grid_kind, shape in self.grid_shape.items()
@@ -1806,7 +1806,7 @@ def _get_data_array(self, data_array: DataArrayOrName) -> xarray.DataArray:
18061806
return self.dataset[data_array]
18071807

18081808
@abc.abstractmethod
1809-
def unpack_index(self, index: Index) -> Tuple[GridKind, Sequence[int]]:
1809+
def unpack_index(self, index: Index) -> tuple[GridKind, Sequence[int]]:
18101810
"""Convert a native index in to a grid kind and dimension indices.
18111811
18121812
Parameters
@@ -1902,7 +1902,7 @@ def wind(
19021902
dimensions=dimensions, sizes=sizes,
19031903
linear_dimension=linear_dimension)
19041904

1905-
def selector_for_index(self, index: Index) -> Dict[Hashable, int]:
1905+
def selector_for_index(self, index: Index) -> dict[Hashable, int]:
19061906
grid_kind, indices = self.unpack_index(index)
19071907
dimensions = self.grid_dimensions[grid_kind]
19081908
return dict(zip(dimensions, indices))

0 commit comments

Comments
 (0)