Skip to content

Commit caca6e1

Browse files
TYP: misc typing in core\indexes\base.py (#35991)
1 parent 675a541 commit caca6e1

File tree

3 files changed

+48
-15
lines changed

3 files changed

+48
-15
lines changed

pandas/core/frame.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1776,13 +1776,13 @@ def from_records(
17761776
arrays = [data[k] for k in columns]
17771777
else:
17781778
arrays = []
1779-
arr_columns = []
1779+
arr_columns_list = []
17801780
for k, v in data.items():
17811781
if k in columns:
1782-
arr_columns.append(k)
1782+
arr_columns_list.append(k)
17831783
arrays.append(v)
17841784

1785-
arrays, arr_columns = reorder_arrays(arrays, arr_columns, columns)
1785+
arrays, arr_columns = reorder_arrays(arrays, arr_columns_list, columns)
17861786

17871787
elif isinstance(data, (np.ndarray, DataFrame)):
17881788
arrays, columns = to_arrays(data, columns)

pandas/core/indexes/base.py

+40-11
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
Hashable,
1111
List,
1212
Optional,
13+
Sequence,
14+
TypeVar,
1315
Union,
1416
)
1517
import warnings
@@ -22,7 +24,7 @@
2224
from pandas._libs.tslibs import OutOfBoundsDatetime, Timestamp
2325
from pandas._libs.tslibs.period import IncompatibleFrequency
2426
from pandas._libs.tslibs.timezones import tz_compare
25-
from pandas._typing import DtypeObj, Label
27+
from pandas._typing import AnyArrayLike, Dtype, DtypeObj, Label
2628
from pandas.compat import set_function_name
2729
from pandas.compat.numpy import function as nv
2830
from pandas.errors import InvalidIndexError
@@ -98,7 +100,7 @@
98100
)
99101

100102
if TYPE_CHECKING:
101-
from pandas import Series
103+
from pandas import RangeIndex, Series
102104

103105

104106
__all__ = ["Index"]
@@ -188,6 +190,9 @@ def _new_Index(cls, d):
188190
return cls.__new__(cls, **d)
189191

190192

193+
_IndexT = TypeVar("_IndexT", bound="Index")
194+
195+
191196
class Index(IndexOpsMixin, PandasObject):
192197
"""
193198
Immutable ndarray implementing an ordered, sliceable set. The basic object
@@ -787,7 +792,13 @@ def repeat(self, repeats, axis=None):
787792
# --------------------------------------------------------------------
788793
# Copying Methods
789794

790-
def copy(self, name=None, deep=False, dtype=None, names=None):
795+
def copy(
796+
self: _IndexT,
797+
name: Optional[Label] = None,
798+
deep: bool = False,
799+
dtype: Optional[Dtype] = None,
800+
names: Optional[Sequence[Label]] = None,
801+
) -> _IndexT:
791802
"""
792803
Make a copy of this object.
793804
@@ -949,10 +960,9 @@ def _format_with_header(
949960
# could have nans
950961
mask = isna(values)
951962
if mask.any():
952-
result = np.array(result)
953-
result[mask] = na_rep
954-
# error: "List[str]" has no attribute "tolist"
955-
result = result.tolist() # type: ignore[attr-defined]
963+
result_arr = np.array(result)
964+
result_arr[mask] = na_rep
965+
result = result_arr.tolist()
956966
else:
957967
result = trim_front(format_array(values, None, justify="left"))
958968
return header + result
@@ -4913,7 +4923,13 @@ def _get_string_slice(self, key: str_t, use_lhs: bool = True, use_rhs: bool = Tr
49134923
# overridden in DatetimeIndex, TimedeltaIndex and PeriodIndex
49144924
raise NotImplementedError
49154925

4916-
def slice_indexer(self, start=None, end=None, step=None, kind=None):
4926+
def slice_indexer(
4927+
self,
4928+
start: Optional[Label] = None,
4929+
end: Optional[Label] = None,
4930+
step: Optional[int] = None,
4931+
kind: Optional[str_t] = None,
4932+
) -> slice:
49174933
"""
49184934
Compute the slice indexer for input labels and step.
49194935
@@ -5513,7 +5529,9 @@ def ensure_index_from_sequences(sequences, names=None):
55135529
return MultiIndex.from_arrays(sequences, names=names)
55145530

55155531

5516-
def ensure_index(index_like, copy: bool = False):
5532+
def ensure_index(
5533+
index_like: Union[AnyArrayLike, Sequence], copy: bool = False
5534+
) -> Index:
55175535
"""
55185536
Ensure that we have an index from some index-like object.
55195537
@@ -5549,7 +5567,18 @@ def ensure_index(index_like, copy: bool = False):
55495567
index_like = index_like.copy()
55505568
return index_like
55515569
if hasattr(index_like, "name"):
5552-
return Index(index_like, name=index_like.name, copy=copy)
5570+
# https://github.com/python/mypy/issues/1424
5571+
# error: Item "ExtensionArray" of "Union[ExtensionArray,
5572+
# Sequence[Any]]" has no attribute "name" [union-attr]
5573+
# error: Item "Sequence[Any]" of "Union[ExtensionArray, Sequence[Any]]"
5574+
# has no attribute "name" [union-attr]
5575+
# error: "Sequence[Any]" has no attribute "name" [attr-defined]
5576+
# error: Item "Sequence[Any]" of "Union[Series, Sequence[Any]]" has no
5577+
# attribute "name" [union-attr]
5578+
# error: Item "Sequence[Any]" of "Union[Any, Sequence[Any]]" has no
5579+
# attribute "name" [union-attr]
5580+
name = index_like.name # type: ignore[union-attr, attr-defined]
5581+
return Index(index_like, name=name, copy=copy)
55535582

55545583
if is_iterator(index_like):
55555584
index_like = list(index_like)
@@ -5604,7 +5633,7 @@ def _validate_join_method(method: str):
56045633
raise ValueError(f"do not recognize join method {method}")
56055634

56065635

5607-
def default_index(n):
5636+
def default_index(n: int) -> "RangeIndex":
56085637
from pandas.core.indexes.range import RangeIndex
56095638

56105639
return RangeIndex(0, n, name=None)

pandas/core/indexes/interval.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
""" define the IntervalIndex """
22
from operator import le, lt
33
import textwrap
4-
from typing import Any, List, Optional, Tuple, Union
4+
from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union, cast
55

66
import numpy as np
77

@@ -56,6 +56,9 @@
5656
from pandas.core.indexes.timedeltas import TimedeltaIndex, timedelta_range
5757
from pandas.core.ops import get_op_result_name
5858

59+
if TYPE_CHECKING:
60+
from pandas import CategoricalIndex
61+
5962
_VALID_CLOSED = {"left", "right", "both", "neither"}
6063
_index_doc_kwargs = dict(ibase._index_doc_kwargs)
6164

@@ -786,6 +789,7 @@ def get_indexer(
786789
right_indexer = self.right.get_indexer(target_as_index.right)
787790
indexer = np.where(left_indexer == right_indexer, left_indexer, -1)
788791
elif is_categorical_dtype(target_as_index.dtype):
792+
target_as_index = cast("CategoricalIndex", target_as_index)
789793
# get an indexer for unique categories then propagate to codes via take_1d
790794
categories_indexer = self.get_indexer(target_as_index.categories)
791795
indexer = take_1d(categories_indexer, target_as_index.codes, fill_value=-1)

0 commit comments

Comments
 (0)