Skip to content

TYP: misc Index return types #57256

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pandas/_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ def __reversed__(self) -> Iterator[_T_co]:
# passed in, a DataFrame is always returned.
NDFrameT = TypeVar("NDFrameT", bound="NDFrame")

IndexT = TypeVar("IndexT", bound="Index")
NumpyIndexT = TypeVar("NumpyIndexT", np.ndarray, "Index")

AxisInt = int
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -10740,7 +10740,7 @@ def _shift_with_freq(self, periods: int, axis: int, freq) -> Self:
f"does not match PeriodIndex freq "
f"{freq_to_period_freqstr(orig_freq.n, orig_freq.name)}"
)
new_ax = index.shift(periods)
new_ax: Index = index.shift(periods)
else:
new_ax = index.shift(periods, freq)

Expand Down
5 changes: 3 additions & 2 deletions pandas/core/indexes/accessors.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from typing import (
TYPE_CHECKING,
NoReturn,
cast,
)
import warnings
Expand Down Expand Up @@ -108,7 +109,7 @@ def _delegate_property_get(self, name: str):
# return the result as a Series
return Series(result, index=index, name=self.name).__finalize__(self._parent)

def _delegate_property_set(self, name: str, value, *args, **kwargs):
def _delegate_property_set(self, name: str, value, *args, **kwargs) -> NoReturn:
raise ValueError(
"modifications to a property of a datetimelike object are not supported. "
"Change values on the original."
Expand Down Expand Up @@ -483,7 +484,7 @@ def to_pytimedelta(self) -> np.ndarray:
return self._get_values().to_pytimedelta()

@property
def components(self):
def components(self) -> DataFrame:
"""
Return a Dataframe of the components of the Timedeltas.

Expand Down
7 changes: 4 additions & 3 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
F,
IgnoreRaise,
IndexLabel,
IndexT,
JoinHow,
Level,
NaPosition,
Expand Down Expand Up @@ -2027,7 +2028,7 @@ def sortlevel(
ascending: bool | list[bool] = True,
sort_remaining=None,
na_position: NaPosition = "first",
):
) -> tuple[Self, np.ndarray]:
"""
For internal compatibility with the Index API.

Expand Down Expand Up @@ -4432,7 +4433,7 @@ def _wrap_reindex_result(self, target, indexer, preserve_names: bool):
target = self._maybe_preserve_names(target, preserve_names)
return target

def _maybe_preserve_names(self, target: Index, preserve_names: bool):
def _maybe_preserve_names(self, target: IndexT, preserve_names: bool) -> IndexT:
if preserve_names and target.nlevels == 1 and target.name != self.name:
target = target.copy(deep=False)
target.name = self.name
Expand Down Expand Up @@ -5987,7 +5988,7 @@ def sort(self, *args, **kwargs):
"""
raise TypeError("cannot sort an Index object in-place, use sort_values instead")

def shift(self, periods: int = 1, freq=None):
def shift(self, periods: int = 1, freq=None) -> Self:
"""
Shift index by desired number of time frequency increments.

Expand Down
4 changes: 2 additions & 2 deletions pandas/core/indexes/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ def _can_partial_date_slice(self, reso: Resolution) -> bool:
def _parsed_string_to_bounds(self, reso: Resolution, parsed):
raise NotImplementedError

def _parse_with_reso(self, label: str):
def _parse_with_reso(self, label: str) -> tuple[datetime, Resolution]:
# overridden by TimedeltaIndex
try:
if self.freq is None or hasattr(self.freq, "rule_code"):
Expand All @@ -295,7 +295,7 @@ def _parse_with_reso(self, label: str):
reso = Resolution.from_attrname(reso_str)
return parsed, reso

def _get_string_slice(self, key: str):
def _get_string_slice(self, key: str) -> slice | npt.NDArray[np.intp]:
# overridden by TimedeltaIndex
parsed, reso = self._parse_with_reso(key)
try:
Expand Down
6 changes: 4 additions & 2 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,9 @@ def snap(self, freq: Frequency = "S") -> DatetimeIndex:
# --------------------------------------------------------------------
# Indexing Methods

def _parsed_string_to_bounds(self, reso: Resolution, parsed: dt.datetime):
def _parsed_string_to_bounds(
self, reso: Resolution, parsed: dt.datetime
) -> tuple[Timestamp, Timestamp]:
"""
Calculate datetime bounds for parsed time string and its resolution.

Expand Down Expand Up @@ -555,7 +557,7 @@ def _parsed_string_to_bounds(self, reso: Resolution, parsed: dt.datetime):
# which localizes parsed.
return start, end

def _parse_with_reso(self, label: str):
def _parse_with_reso(self, label: str) -> tuple[Timestamp, Resolution]:
parsed, reso = super()._parse_with_reso(label)

parsed = Timestamp(parsed)
Expand Down
3 changes: 2 additions & 1 deletion pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
F,
IgnoreRaise,
IndexLabel,
IndexT,
Scalar,
Self,
Shape,
Expand Down Expand Up @@ -2727,7 +2728,7 @@ def _wrap_reindex_result(self, target, indexer, preserve_names: bool):
target = self._maybe_preserve_names(target, preserve_names)
return target

def _maybe_preserve_names(self, target: Index, preserve_names: bool) -> Index:
def _maybe_preserve_names(self, target: IndexT, preserve_names: bool) -> IndexT:
if (
preserve_names
and target.nlevels == self.nlevels
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/indexes/range.py
Original file line number Diff line number Diff line change
Expand Up @@ -876,7 +876,7 @@ def _difference(self, other, sort=None):

def symmetric_difference(
self, other, result_name: Hashable | None = None, sort=None
):
) -> Index:
if not isinstance(other, RangeIndex) or sort is not None:
return super().symmetric_difference(other, result_name, sort)

Expand Down
6 changes: 5 additions & 1 deletion pandas/core/indexes/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from pandas.core.indexes.extension import inherit_names

if TYPE_CHECKING:
from pandas._libs import NaTType
from pandas._typing import DtypeObj


Expand Down Expand Up @@ -245,7 +246,10 @@ def get_loc(self, key):

return Index.get_loc(self, key)

def _parse_with_reso(self, label: str):
# error: Return type "tuple[Timedelta | NaTType, None]" of "_parse_with_reso"
# incompatible with return type "tuple[datetime, Resolution]" in supertype
# "DatetimeIndexOpsMixin"
def _parse_with_reso(self, label: str) -> tuple[Timedelta | NaTType, None]: # type: ignore[override]
# the "with_reso" is a no-op for TimedeltaIndex
parsed = Timedelta(label)
return parsed, None
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -761,5 +761,5 @@ exclude_lines = [
directory = "coverage_html_report"

[tool.codespell]
ignore-words-list = "blocs, coo, hist, nd, sav, ser, recuse, nin, timere, expec, expecs"
ignore-words-list = "blocs, coo, hist, nd, sav, ser, recuse, nin, timere, expec, expecs, indext"
ignore-regex = 'https://([\w/\.])+'