Skip to content

Commit 88df92f

Browse files
authored
TYP: indexes (#40744)
1 parent bbbd15c commit 88df92f

17 files changed

+121
-107
lines changed

pandas/core/arrays/datetimes.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ class DatetimeArray(dtl.TimelikeOps, dtl.DatelikeOps):
190190
_infer_matches = ("datetime", "datetime64", "date")
191191

192192
# define my properties & methods for delegation
193-
_bool_ops = [
193+
_bool_ops: list[str] = [
194194
"is_month_start",
195195
"is_month_end",
196196
"is_quarter_start",
@@ -199,8 +199,8 @@ class DatetimeArray(dtl.TimelikeOps, dtl.DatelikeOps):
199199
"is_year_end",
200200
"is_leap_year",
201201
]
202-
_object_ops = ["freq", "tz"]
203-
_field_ops = [
202+
_object_ops: list[str] = ["freq", "tz"]
203+
_field_ops: list[str] = [
204204
"year",
205205
"month",
206206
"day",
@@ -220,9 +220,9 @@ class DatetimeArray(dtl.TimelikeOps, dtl.DatelikeOps):
220220
"microsecond",
221221
"nanosecond",
222222
]
223-
_other_ops = ["date", "time", "timetz"]
224-
_datetimelike_ops = _field_ops + _object_ops + _bool_ops + _other_ops
225-
_datetimelike_methods = [
223+
_other_ops: list[str] = ["date", "time", "timetz"]
224+
_datetimelike_ops: list[str] = _field_ops + _object_ops + _bool_ops + _other_ops
225+
_datetimelike_methods: list[str] = [
226226
"to_period",
227227
"tz_localize",
228228
"tz_convert",

pandas/core/arrays/interval.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@
8787

8888
IntervalArrayT = TypeVar("IntervalArrayT", bound="IntervalArray")
8989

90-
_interval_shared_docs = {}
90+
_interval_shared_docs: dict[str, str] = {}
9191

9292
_shared_docs_kwargs = {
9393
"klass": "IntervalArray",

pandas/core/arrays/period.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -157,9 +157,9 @@ class PeriodArray(PeriodMixin, dtl.DatelikeOps):
157157

158158
# Names others delegate to us
159159
_other_ops: list[str] = []
160-
_bool_ops = ["is_leap_year"]
161-
_object_ops = ["start_time", "end_time", "freq"]
162-
_field_ops = [
160+
_bool_ops: list[str] = ["is_leap_year"]
161+
_object_ops: list[str] = ["start_time", "end_time", "freq"]
162+
_field_ops: list[str] = [
163163
"year",
164164
"month",
165165
"day",

pandas/core/generic.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1797,9 +1797,9 @@ def _drop_labels_or_levels(self, keys, axis: int = 0):
17971797
17981798
Parameters
17991799
----------
1800-
keys: str or list of str
1800+
keys : str or list of str
18011801
labels or levels to drop
1802-
axis: int, default 0
1802+
axis : int, default 0
18031803
Axis that levels are associated with (0 for index, 1 for columns)
18041804
18051805
Returns

pandas/core/groupby/base.py

+11-6
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@
33
hold the allowlist of methods that are exposed on the
44
SeriesGroupBy and the DataFrameGroupBy objects.
55
"""
6+
from __future__ import annotations
7+
68
import collections
7-
from typing import List
89

910
from pandas._typing import final
1011

@@ -19,7 +20,7 @@
1920

2021

2122
class ShallowMixin(PandasObject):
22-
_attributes: List[str] = []
23+
_attributes: list[str] = []
2324

2425
@final
2526
def _shallow_copy(self, obj, **kwargs):
@@ -39,7 +40,7 @@ class GotItemMixin(PandasObject):
3940
Provide the groupby facilities to the mixed object.
4041
"""
4142

42-
_attributes: List[str]
43+
_attributes: list[str]
4344

4445
@final
4546
def _gotitem(self, key, ndim, subset=None):
@@ -106,12 +107,16 @@ def _gotitem(self, key, ndim, subset=None):
106107
| plotting_methods
107108
)
108109

109-
series_apply_allowlist = (
110+
series_apply_allowlist: frozenset[str] = (
110111
common_apply_allowlist
111-
| {"nlargest", "nsmallest", "is_monotonic_increasing", "is_monotonic_decreasing"}
112+
| frozenset(
113+
{"nlargest", "nsmallest", "is_monotonic_increasing", "is_monotonic_decreasing"}
114+
)
112115
) | frozenset(["dtype", "unique"])
113116

114-
dataframe_apply_allowlist = common_apply_allowlist | frozenset(["dtypes", "corrwith"])
117+
dataframe_apply_allowlist: frozenset[str] = common_apply_allowlist | frozenset(
118+
["dtypes", "corrwith"]
119+
)
115120

116121
# cythonized transformations or canned "agg+broadcast", which do not
117122
# require postprocessing of the result by transform.

pandas/core/indexes/base.py

+14-14
Original file line numberDiff line numberDiff line change
@@ -173,15 +173,15 @@
173173

174174
_unsortable_types = frozenset(("mixed", "mixed-integer"))
175175

176-
_index_doc_kwargs = {
176+
_index_doc_kwargs: dict[str, str] = {
177177
"klass": "Index",
178178
"inplace": "",
179179
"target_klass": "Index",
180180
"raises_section": "",
181181
"unique": "Index",
182182
"duplicated": "np.ndarray",
183183
}
184-
_index_shared_docs = {}
184+
_index_shared_docs: dict[str, str] = {}
185185
str_t = str
186186

187187

@@ -1189,7 +1189,7 @@ def _format_with_header(
11891189
return header + result
11901190

11911191
@final
1192-
def to_native_types(self, slicer=None, **kwargs):
1192+
def to_native_types(self, slicer=None, **kwargs) -> np.ndarray:
11931193
"""
11941194
Format specified values of `self` and return them.
11951195
@@ -4388,7 +4388,7 @@ def memory_usage(self, deep: bool = False) -> int:
43884388
return result
43894389

43904390
@final
4391-
def where(self, cond, other=None):
4391+
def where(self, cond, other=None) -> Index:
43924392
"""
43934393
Replace values where the condition is False.
43944394
@@ -4604,7 +4604,7 @@ def _can_hold_identifiers_and_holds_name(self, name) -> bool:
46044604
return name in self
46054605
return False
46064606

4607-
def append(self, other):
4607+
def append(self, other) -> Index:
46084608
"""
46094609
Append a collection of Index options together.
46104610
@@ -4614,7 +4614,7 @@ def append(self, other):
46144614
46154615
Returns
46164616
-------
4617-
appended : Index
4617+
Index
46184618
"""
46194619
to_concat = [self]
46204620

@@ -4844,7 +4844,7 @@ def asof(self, label):
48444844
loc = loc.indices(len(self))[-1]
48454845
return self[loc]
48464846

4847-
def asof_locs(self, where: Index, mask) -> np.ndarray:
4847+
def asof_locs(self, where: Index, mask: np.ndarray) -> np.ndarray:
48484848
"""
48494849
Return the locations (indices) of labels in the index.
48504850
@@ -4861,21 +4861,21 @@ def asof_locs(self, where: Index, mask) -> np.ndarray:
48614861
----------
48624862
where : Index
48634863
An Index consisting of an array of timestamps.
4864-
mask : array-like
4864+
mask : np.ndarray[bool]
48654865
Array of booleans denoting where values in the original
48664866
data are not NA.
48674867
48684868
Returns
48694869
-------
4870-
numpy.ndarray
4870+
np.ndarray[np.intp]
48714871
An array of locations (indices) of the labels from the Index
48724872
which correspond to the return values of the `asof` function
48734873
for every element in `where`.
48744874
"""
48754875
locs = self._values[mask].searchsorted(where._values, side="right")
48764876
locs = np.where(locs > 0, locs - 1, 0)
48774877

4878-
result = np.arange(len(self))[mask].take(locs)
4878+
result = np.arange(len(self), dtype=np.intp)[mask].take(locs)
48794879

48804880
# TODO: overload return type of ExtensionArray.__getitem__
48814881
first_value = cast(Any, self._values[mask.argmax()])
@@ -5048,7 +5048,7 @@ def argsort(self, *args, **kwargs) -> np.ndarray:
50485048
50495049
Returns
50505050
-------
5051-
numpy.ndarray
5051+
np.ndarray[np.intp]
50525052
Integer indices that would sort the index if used as
50535053
an indexer.
50545054
@@ -5836,7 +5836,7 @@ def delete(self, loc) -> Index:
58365836
Returns
58375837
-------
58385838
Index
5839-
New Index with passed location(-s) deleted.
5839+
Will be same type as self, except for RangeIndex.
58405840
58415841
See Also
58425842
--------
@@ -6350,8 +6350,8 @@ def _maybe_cast_data_without_dtype(subarr):
63506350

63516351
elif inferred == "interval":
63526352
try:
6353-
data = IntervalArray._from_sequence(subarr, copy=False)
6354-
return data
6353+
ia_data = IntervalArray._from_sequence(subarr, copy=False)
6354+
return ia_data
63556355
except (ValueError, TypeError):
63566356
# GH27172: mixed closed Intervals --> object dtype
63576357
pass

pandas/core/indexes/category.py

+13-14
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1+
from __future__ import annotations
2+
13
from typing import (
24
Any,
35
Hashable,
4-
List,
5-
Optional,
66
)
77
import warnings
88

@@ -50,7 +50,7 @@
5050
inherit_names,
5151
)
5252

53-
_index_doc_kwargs = dict(ibase._index_doc_kwargs)
53+
_index_doc_kwargs: dict[str, str] = dict(ibase._index_doc_kwargs)
5454
_index_doc_kwargs.update({"target_klass": "CategoricalIndex"})
5555

5656

@@ -216,10 +216,10 @@ def __new__(
216216
data=None,
217217
categories=None,
218218
ordered=None,
219-
dtype: Optional[Dtype] = None,
220-
copy=False,
221-
name=None,
222-
):
219+
dtype: Dtype | None = None,
220+
copy: bool = False,
221+
name: Hashable = None,
222+
) -> CategoricalIndex:
223223

224224
name = maybe_extract_name(name, data, cls)
225225

@@ -239,7 +239,7 @@ def _shallow_copy(
239239
self,
240240
values: Categorical,
241241
name: Hashable = no_default,
242-
):
242+
) -> CategoricalIndex:
243243
name = self._name if name is no_default else name
244244

245245
if values is not None:
@@ -349,7 +349,7 @@ def _format_attrs(self):
349349
attrs.append(("length", len(self)))
350350
return attrs
351351

352-
def _format_with_header(self, header: List[str], na_rep: str = "NaN") -> List[str]:
352+
def _format_with_header(self, header: list[str], na_rep: str = "NaN") -> list[str]:
353353
from pandas.io.formats.printing import pprint_thing
354354

355355
result = [
@@ -422,10 +422,9 @@ def reindex(self, target, method=None, level=None, limit=None, tolerance=None):
422422

423423
target = ibase.ensure_index(target)
424424

425-
missing: List[int]
426425
if self.equals(target):
427426
indexer = None
428-
missing = []
427+
missing = np.array([], dtype=np.intp)
429428
else:
430429
indexer, missing = self.get_indexer_non_unique(np.array(target))
431430

@@ -494,8 +493,8 @@ def _maybe_cast_indexer(self, key) -> int:
494493
def _get_indexer(
495494
self,
496495
target: Index,
497-
method: Optional[str] = None,
498-
limit: Optional[int] = None,
496+
method: str | None = None,
497+
limit: int | None = None,
499498
tolerance=None,
500499
) -> np.ndarray:
501500

@@ -626,7 +625,7 @@ def map(self, mapper):
626625
mapped = self._values.map(mapper)
627626
return Index(mapped, name=self.name)
628627

629-
def _concat(self, to_concat: List[Index], name: Hashable) -> Index:
628+
def _concat(self, to_concat: list[Index], name: Hashable) -> Index:
630629
# if calling index is category, don't check dtype of others
631630
try:
632631
codes = np.concatenate([self._is_dtype_compat(c).codes for c in to_concat])

0 commit comments

Comments
 (0)