Skip to content

Commit 96cf77a

Browse files
max-sixtypre-commit-ci[bot]headtr1ck
authored
Convert indexes.py to use Self for typing (#8217)
* Convert `Variable` to use `Self` for typing I wanted to do this separately, as it's the only one that adds some casts. And given the ratio of impact-to-potential-merge-conflicts, I didn't want to slow the other PR down, even if it seems to be OK. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update xarray/core/indexes.py Co-authored-by: Michael Niklas <[email protected]> * Update xarray/core/indexes.py Co-authored-by: Michael Niklas <[email protected]> * Update xarray/core/indexes.py Co-authored-by: Michael Niklas <[email protected]> * Update xarray/core/indexes.py Co-authored-by: Michael Niklas <[email protected]> * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Michael Niklas <[email protected]>
1 parent f60c1a3 commit 96cf77a

File tree

1 file changed

+32
-31
lines changed

1 file changed

+32
-31
lines changed

xarray/core/indexes.py

+32-31
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
)
2525

2626
if TYPE_CHECKING:
27-
from xarray.core.types import ErrorOptions, JoinOptions, T_Index
27+
from xarray.core.types import ErrorOptions, JoinOptions, Self
2828
from xarray.core.variable import Variable
2929

3030

@@ -60,11 +60,11 @@ class Index:
6060

6161
@classmethod
6262
def from_variables(
63-
cls: type[T_Index],
63+
cls,
6464
variables: Mapping[Any, Variable],
6565
*,
6666
options: Mapping[str, Any],
67-
) -> T_Index:
67+
) -> Self:
6868
"""Create a new index object from one or more coordinate variables.
6969
7070
This factory method must be implemented in all subclasses of Index.
@@ -88,11 +88,11 @@ def from_variables(
8888

8989
@classmethod
9090
def concat(
91-
cls: type[T_Index],
92-
indexes: Sequence[T_Index],
91+
cls,
92+
indexes: Sequence[Self],
9393
dim: Hashable,
9494
positions: Iterable[Iterable[int]] | None = None,
95-
) -> T_Index:
95+
) -> Self:
9696
"""Create a new index by concatenating one or more indexes of the same
9797
type.
9898
@@ -120,9 +120,7 @@ def concat(
120120
raise NotImplementedError()
121121

122122
@classmethod
123-
def stack(
124-
cls: type[T_Index], variables: Mapping[Any, Variable], dim: Hashable
125-
) -> T_Index:
123+
def stack(cls, variables: Mapping[Any, Variable], dim: Hashable) -> Self:
126124
"""Create a new index by stacking coordinate variables into a single new
127125
dimension.
128126
@@ -208,8 +206,8 @@ def to_pandas_index(self) -> pd.Index:
208206
raise TypeError(f"{self!r} cannot be cast to a pandas.Index object")
209207

210208
def isel(
211-
self: T_Index, indexers: Mapping[Any, int | slice | np.ndarray | Variable]
212-
) -> T_Index | None:
209+
self, indexers: Mapping[Any, int | slice | np.ndarray | Variable]
210+
) -> Self | None:
213211
"""Maybe returns a new index from the current index itself indexed by
214212
positional indexers.
215213
@@ -264,7 +262,7 @@ def sel(self, labels: dict[Any, Any]) -> IndexSelResult:
264262
"""
265263
raise NotImplementedError(f"{self!r} doesn't support label-based selection")
266264

267-
def join(self: T_Index, other: T_Index, how: JoinOptions = "inner") -> T_Index:
265+
def join(self, other: Self, how: JoinOptions = "inner") -> Self:
268266
"""Return a new index from the combination of this index with another
269267
index of the same type.
270268
@@ -286,7 +284,7 @@ def join(self: T_Index, other: T_Index, how: JoinOptions = "inner") -> T_Index:
286284
f"{self!r} doesn't support alignment with inner/outer join method"
287285
)
288286

289-
def reindex_like(self: T_Index, other: T_Index) -> dict[Hashable, Any]:
287+
def reindex_like(self, other: Self) -> dict[Hashable, Any]:
290288
"""Query the index with another index of the same type.
291289
292290
Implementation is optional but required in order to support alignment.
@@ -304,7 +302,7 @@ def reindex_like(self: T_Index, other: T_Index) -> dict[Hashable, Any]:
304302
"""
305303
raise NotImplementedError(f"{self!r} doesn't support re-indexing labels")
306304

307-
def equals(self: T_Index, other: T_Index) -> bool:
305+
def equals(self, other: Self) -> bool:
308306
"""Compare this index with another index of the same type.
309307
310308
Implementation is optional but required in order to support alignment.
@@ -321,7 +319,7 @@ def equals(self: T_Index, other: T_Index) -> bool:
321319
"""
322320
raise NotImplementedError()
323321

324-
def roll(self: T_Index, shifts: Mapping[Any, int]) -> T_Index | None:
322+
def roll(self, shifts: Mapping[Any, int]) -> Self | None:
325323
"""Roll this index by an offset along one or more dimensions.
326324
327325
This method can be re-implemented in subclasses of Index, e.g., when the
@@ -347,10 +345,10 @@ def roll(self: T_Index, shifts: Mapping[Any, int]) -> T_Index | None:
347345
return None
348346

349347
def rename(
350-
self: T_Index,
348+
self,
351349
name_dict: Mapping[Any, Hashable],
352350
dims_dict: Mapping[Any, Hashable],
353-
) -> T_Index:
351+
) -> Self:
354352
"""Maybe update the index with new coordinate and dimension names.
355353
356354
This method should be re-implemented in subclasses of Index if it has
@@ -377,7 +375,7 @@ def rename(
377375
"""
378376
return self
379377

380-
def copy(self: T_Index, deep: bool = True) -> T_Index:
378+
def copy(self, deep: bool = True) -> Self:
381379
"""Return a (deep) copy of this index.
382380
383381
Implementation in subclasses of Index is optional. The base class
@@ -396,15 +394,13 @@ def copy(self: T_Index, deep: bool = True) -> T_Index:
396394
"""
397395
return self._copy(deep=deep)
398396

399-
def __copy__(self: T_Index) -> T_Index:
397+
def __copy__(self) -> Self:
400398
return self.copy(deep=False)
401399

402400
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Index:
403401
return self._copy(deep=True, memo=memo)
404402

405-
def _copy(
406-
self: T_Index, deep: bool = True, memo: dict[int, Any] | None = None
407-
) -> T_Index:
403+
def _copy(self, deep: bool = True, memo: dict[int, Any] | None = None) -> Self:
408404
cls = self.__class__
409405
copied = cls.__new__(cls)
410406
if deep:
@@ -414,7 +410,7 @@ def _copy(
414410
copied.__dict__.update(self.__dict__)
415411
return copied
416412

417-
def __getitem__(self: T_Index, indexer: Any) -> T_Index:
413+
def __getitem__(self, indexer: Any) -> Self:
418414
raise NotImplementedError()
419415

420416
def _repr_inline_(self, max_width):
@@ -674,10 +670,10 @@ def _concat_indexes(indexes, dim, positions=None) -> pd.Index:
674670
@classmethod
675671
def concat(
676672
cls,
677-
indexes: Sequence[PandasIndex],
673+
indexes: Sequence[Self],
678674
dim: Hashable,
679675
positions: Iterable[Iterable[int]] | None = None,
680-
) -> PandasIndex:
676+
) -> Self:
681677
new_pd_index = cls._concat_indexes(indexes, dim, positions)
682678

683679
if not indexes:
@@ -800,7 +796,11 @@ def equals(self, other: Index):
800796
return False
801797
return self.index.equals(other.index) and self.dim == other.dim
802798

803-
def join(self: PandasIndex, other: PandasIndex, how: str = "inner") -> PandasIndex:
799+
def join(
800+
self,
801+
other: Self,
802+
how: str = "inner",
803+
) -> Self:
804804
if how == "outer":
805805
index = self.index.union(other.index)
806806
else:
@@ -811,7 +811,7 @@ def join(self: PandasIndex, other: PandasIndex, how: str = "inner") -> PandasInd
811811
return type(self)(index, self.dim, coord_dtype=coord_dtype)
812812

813813
def reindex_like(
814-
self, other: PandasIndex, method=None, tolerance=None
814+
self, other: Self, method=None, tolerance=None
815815
) -> dict[Hashable, Any]:
816816
if not self.index.is_unique:
817817
raise ValueError(
@@ -963,12 +963,12 @@ def from_variables(
963963
return obj
964964

965965
@classmethod
966-
def concat( # type: ignore[override]
966+
def concat(
967967
cls,
968-
indexes: Sequence[PandasMultiIndex],
968+
indexes: Sequence[Self],
969969
dim: Hashable,
970970
positions: Iterable[Iterable[int]] | None = None,
971-
) -> PandasMultiIndex:
971+
) -> Self:
972972
new_pd_index = cls._concat_indexes(indexes, dim, positions)
973973

974974
if not indexes:
@@ -1602,7 +1602,7 @@ def to_pandas_indexes(self) -> Indexes[pd.Index]:
16021602
return Indexes(indexes, self._variables, index_type=pd.Index)
16031603

16041604
def copy_indexes(
1605-
self, deep: bool = True, memo: dict[int, Any] | None = None
1605+
self, deep: bool = True, memo: dict[int, T_PandasOrXarrayIndex] | None = None
16061606
) -> tuple[dict[Hashable, T_PandasOrXarrayIndex], dict[Hashable, Variable]]:
16071607
"""Return a new dictionary with copies of indexes, preserving
16081608
unique indexes.
@@ -1619,6 +1619,7 @@ def copy_indexes(
16191619
new_indexes = {}
16201620
new_index_vars = {}
16211621

1622+
idx: T_PandasOrXarrayIndex
16221623
for idx, coords in self.group_by_index():
16231624
if isinstance(idx, pd.Index):
16241625
convert_new_idx = True

0 commit comments

Comments
 (0)