Skip to content

Commit 6cc880c

Browse files
committed
TYP: simple return types (pandas-dev#54786)
* Return None * Return simple types * ruff false positive * isort+mypy * typo, use " for cast * SingleArrayManager.dtype can also be a numpy dtype * comments + test assert on CI * wider return types at the cost of one fewer mypy ignore * DatetimeArray reaches IntervalArray._combined * avoid some ignores * remove assert False
1 parent ac18ef0 commit 6cc880c

39 files changed

+229
-143
lines changed

pandas/_testing/_io.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ def round_trip_localpath(writer, reader, path: str | None = None):
118118
return obj
119119

120120

121-
def write_to_compressed(compression, path, data, dest: str = "test"):
121+
def write_to_compressed(compression, path, data, dest: str = "test") -> None:
122122
"""
123123
Write data to a compressed file.
124124

pandas/arrays/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
]
3737

3838

39-
def __getattr__(name: str):
39+
def __getattr__(name: str) -> type[NumpyExtensionArray]:
4040
if name == "PandasArray":
4141
# GH#53694
4242
import warnings

pandas/compat/pickle_compat.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
from collections.abc import Generator
2727

2828

29-
def load_reduce(self):
29+
def load_reduce(self) -> None:
3030
stack = self.stack
3131
args = stack.pop()
3232
func = stack[-1]

pandas/conftest.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -491,7 +491,7 @@ def box_with_array(request):
491491

492492

493493
@pytest.fixture
494-
def dict_subclass():
494+
def dict_subclass() -> type[dict]:
495495
"""
496496
Fixture for a dictionary subclass.
497497
"""
@@ -504,7 +504,7 @@ def __init__(self, *args, **kwargs) -> None:
504504

505505

506506
@pytest.fixture
507-
def non_dict_mapping_subclass():
507+
def non_dict_mapping_subclass() -> type[abc.Mapping]:
508508
"""
509509
Fixture for a non-mapping dictionary subclass.
510510
"""

pandas/core/apply.py

+11-9
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,9 @@
5454

5555
if TYPE_CHECKING:
5656
from collections.abc import (
57+
Generator,
5758
Hashable,
5859
Iterable,
59-
Iterator,
6060
Sequence,
6161
)
6262

@@ -253,7 +253,7 @@ def transform(self) -> DataFrame | Series:
253253

254254
return result
255255

256-
def transform_dict_like(self, func):
256+
def transform_dict_like(self, func) -> DataFrame:
257257
"""
258258
Compute transform in the case of a dict-like func
259259
"""
@@ -315,7 +315,7 @@ def compute_list_like(
315315
op_name: Literal["agg", "apply"],
316316
selected_obj: Series | DataFrame,
317317
kwargs: dict[str, Any],
318-
) -> tuple[list[Hashable], list[Any]]:
318+
) -> tuple[list[Hashable] | Index, list[Any]]:
319319
"""
320320
Compute agg/apply results for like-like input.
321321
@@ -330,7 +330,7 @@ def compute_list_like(
330330
331331
Returns
332332
-------
333-
keys : list[hashable]
333+
keys : list[Hashable] or Index
334334
Index labels for result.
335335
results : list
336336
Data for result. When aggregating with a Series, this can contain any
@@ -370,12 +370,14 @@ def compute_list_like(
370370
new_res = getattr(colg, op_name)(func, *args, **kwargs)
371371
results.append(new_res)
372372
indices.append(index)
373-
keys = selected_obj.columns.take(indices)
373+
# error: Incompatible types in assignment (expression has type "Any |
374+
# Index", variable has type "list[Any | Callable[..., Any] | str]")
375+
keys = selected_obj.columns.take(indices) # type: ignore[assignment]
374376

375377
return keys, results
376378

377379
def wrap_results_list_like(
378-
self, keys: list[Hashable], results: list[Series | DataFrame]
380+
self, keys: Iterable[Hashable], results: list[Series | DataFrame]
379381
):
380382
from pandas.core.reshape.concat import concat
381383

@@ -772,7 +774,7 @@ def result_columns(self) -> Index:
772774

773775
@property
774776
@abc.abstractmethod
775-
def series_generator(self) -> Iterator[Series]:
777+
def series_generator(self) -> Generator[Series, None, None]:
776778
pass
777779

778780
@abc.abstractmethod
@@ -1014,7 +1016,7 @@ class FrameRowApply(FrameApply):
10141016
axis: AxisInt = 0
10151017

10161018
@property
1017-
def series_generator(self):
1019+
def series_generator(self) -> Generator[Series, None, None]:
10181020
return (self.obj._ixs(i, axis=1) for i in range(len(self.columns)))
10191021

10201022
@property
@@ -1075,7 +1077,7 @@ def apply_broadcast(self, target: DataFrame) -> DataFrame:
10751077
return result.T
10761078

10771079
@property
1078-
def series_generator(self):
1080+
def series_generator(self) -> Generator[Series, None, None]:
10791081
values = self.values
10801082
values = ensure_wrapped_if_datetimelike(values)
10811083
assert len(values) > 0

pandas/core/arrays/arrow/extension_types.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def __ne__(self, other) -> bool:
4848
def __hash__(self) -> int:
4949
return hash((str(self), self.freq))
5050

51-
def to_pandas_dtype(self):
51+
def to_pandas_dtype(self) -> PeriodDtype:
5252
return PeriodDtype(freq=self.freq)
5353

5454

@@ -105,7 +105,7 @@ def __ne__(self, other) -> bool:
105105
def __hash__(self) -> int:
106106
return hash((str(self), str(self.subtype), self.closed))
107107

108-
def to_pandas_dtype(self):
108+
def to_pandas_dtype(self) -> IntervalDtype:
109109
return IntervalDtype(self.subtype.to_pandas_dtype(), self.closed)
110110

111111

pandas/core/arrays/categorical.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2410,7 +2410,7 @@ def _mode(self, dropna: bool = True) -> Categorical:
24102410
# ------------------------------------------------------------------
24112411
# ExtensionArray Interface
24122412

2413-
def unique(self):
2413+
def unique(self) -> Self:
24142414
"""
24152415
Return the ``Categorical`` which ``categories`` and ``codes`` are
24162416
unique.

pandas/core/arrays/interval.py

+22-16
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@
110110
)
111111

112112

113-
IntervalSideT = Union[TimeArrayLike, np.ndarray]
113+
IntervalSide = Union[TimeArrayLike, np.ndarray]
114114
IntervalOrNA = Union[Interval, float]
115115

116116
_interval_shared_docs: dict[str, str] = {}
@@ -219,8 +219,8 @@ def ndim(self) -> Literal[1]:
219219
return 1
220220

221221
# To make mypy recognize the fields
222-
_left: IntervalSideT
223-
_right: IntervalSideT
222+
_left: IntervalSide
223+
_right: IntervalSide
224224
_dtype: IntervalDtype
225225

226226
# ---------------------------------------------------------------------
@@ -237,8 +237,8 @@ def __new__(
237237
data = extract_array(data, extract_numpy=True)
238238

239239
if isinstance(data, cls):
240-
left: IntervalSideT = data._left
241-
right: IntervalSideT = data._right
240+
left: IntervalSide = data._left
241+
right: IntervalSide = data._right
242242
closed = closed or data.closed
243243
dtype = IntervalDtype(left.dtype, closed=closed)
244244
else:
@@ -280,8 +280,8 @@ def __new__(
280280
@classmethod
281281
def _simple_new(
282282
cls,
283-
left: IntervalSideT,
284-
right: IntervalSideT,
283+
left: IntervalSide,
284+
right: IntervalSide,
285285
dtype: IntervalDtype,
286286
) -> Self:
287287
result = IntervalMixin.__new__(cls)
@@ -299,7 +299,7 @@ def _ensure_simple_new_inputs(
299299
closed: IntervalClosedType | None = None,
300300
copy: bool = False,
301301
dtype: Dtype | None = None,
302-
) -> tuple[IntervalSideT, IntervalSideT, IntervalDtype]:
302+
) -> tuple[IntervalSide, IntervalSide, IntervalDtype]:
303303
"""Ensure correctness of input parameters for cls._simple_new."""
304304
from pandas.core.indexes.base import ensure_index
305305

@@ -1031,8 +1031,8 @@ def _concat_same_type(cls, to_concat: Sequence[IntervalArray]) -> Self:
10311031
raise ValueError("Intervals must all be closed on the same side.")
10321032
closed = closed_set.pop()
10331033

1034-
left = np.concatenate([interval.left for interval in to_concat])
1035-
right = np.concatenate([interval.right for interval in to_concat])
1034+
left: IntervalSide = np.concatenate([interval.left for interval in to_concat])
1035+
right: IntervalSide = np.concatenate([interval.right for interval in to_concat])
10361036

10371037
left, right, dtype = cls._ensure_simple_new_inputs(left, right, closed=closed)
10381038

@@ -1283,7 +1283,7 @@ def _format_space(self) -> str:
12831283
# Vectorized Interval Properties/Attributes
12841284

12851285
@property
1286-
def left(self):
1286+
def left(self) -> Index:
12871287
"""
12881288
Return the left endpoints of each Interval in the IntervalArray as an Index.
12891289
@@ -1303,7 +1303,7 @@ def left(self):
13031303
return Index(self._left, copy=False)
13041304

13051305
@property
1306-
def right(self):
1306+
def right(self) -> Index:
13071307
"""
13081308
Return the right endpoints of each Interval in the IntervalArray as an Index.
13091309
@@ -1855,11 +1855,17 @@ def isin(self, values) -> npt.NDArray[np.bool_]:
18551855
return isin(self.astype(object), values.astype(object))
18561856

18571857
@property
1858-
def _combined(self) -> IntervalSideT:
1859-
left = self.left._values.reshape(-1, 1)
1860-
right = self.right._values.reshape(-1, 1)
1858+
def _combined(self) -> IntervalSide:
1859+
# error: Item "ExtensionArray" of "ExtensionArray | ndarray[Any, Any]"
1860+
# has no attribute "reshape" [union-attr]
1861+
left = self.left._values.reshape(-1, 1) # type: ignore[union-attr]
1862+
right = self.right._values.reshape(-1, 1) # type: ignore[union-attr]
18611863
if needs_i8_conversion(left.dtype):
1862-
comb = left._concat_same_type([left, right], axis=1)
1864+
# error: Item "ndarray[Any, Any]" of "Any | ndarray[Any, Any]" has
1865+
# no attribute "_concat_same_type"
1866+
comb = left._concat_same_type( # type: ignore[union-attr]
1867+
[left, right], axis=1
1868+
)
18631869
else:
18641870
comb = np.concatenate([left, right], axis=1)
18651871
return comb

pandas/core/arrays/period.py

+3-6
Original file line numberDiff line numberDiff line change
@@ -948,7 +948,7 @@ def _check_timedeltalike_freq_compat(self, other):
948948
return lib.item_from_zerodim(delta)
949949

950950

951-
def raise_on_incompatible(left, right):
951+
def raise_on_incompatible(left, right) -> IncompatibleFrequency:
952952
"""
953953
Helper function to render a consistent error message when raising
954954
IncompatibleFrequency.
@@ -1089,7 +1089,7 @@ def validate_dtype_freq(dtype, freq: timedelta | str | None) -> BaseOffset:
10891089

10901090

10911091
def validate_dtype_freq(
1092-
dtype, freq: BaseOffsetT | timedelta | str | None
1092+
dtype, freq: BaseOffsetT | BaseOffset | timedelta | str | None
10931093
) -> BaseOffsetT:
10941094
"""
10951095
If both a dtype and a freq are available, ensure they match. If only
@@ -1110,10 +1110,7 @@ def validate_dtype_freq(
11101110
IncompatibleFrequency : mismatch between dtype and freq
11111111
"""
11121112
if freq is not None:
1113-
# error: Incompatible types in assignment (expression has type
1114-
# "BaseOffset", variable has type "Union[BaseOffsetT, timedelta,
1115-
# str, None]")
1116-
freq = to_offset(freq) # type: ignore[assignment]
1113+
freq = to_offset(freq)
11171114

11181115
if dtype is not None:
11191116
dtype = pandas_dtype(dtype)

pandas/core/arrays/sparse/array.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -702,7 +702,9 @@ def npoints(self) -> int:
702702
"""
703703
return self.sp_index.npoints
704704

705-
def isna(self):
705+
# error: Return type "SparseArray" of "isna" incompatible with return type
706+
# "ndarray[Any, Any] | ExtensionArraySupportsAnyAll" in supertype "ExtensionArray"
707+
def isna(self) -> Self: # type: ignore[override]
706708
# If null fill value, we want SparseDtype[bool, true]
707709
# to preserve the same memory usage.
708710
dtype = SparseDtype(bool, self._null_fill_value)
@@ -1421,7 +1423,7 @@ def all(self, axis=None, *args, **kwargs):
14211423

14221424
return values.all()
14231425

1424-
def any(self, axis: AxisInt = 0, *args, **kwargs):
1426+
def any(self, axis: AxisInt = 0, *args, **kwargs) -> bool:
14251427
"""
14261428
Tests whether at least one of elements evaluate True
14271429

pandas/core/arrays/string_.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
NumpySorter,
6060
NumpyValueArrayLike,
6161
Scalar,
62+
Self,
6263
npt,
6364
type_t,
6465
)
@@ -135,7 +136,7 @@ def type(self) -> type[str]:
135136
return str
136137

137138
@classmethod
138-
def construct_from_string(cls, string):
139+
def construct_from_string(cls, string) -> Self:
139140
"""
140141
Construct a StringDtype from a string.
141142

pandas/core/arrays/string_arrow.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@
5353
npt,
5454
)
5555

56+
from pandas import Series
57+
5658

5759
ArrowStringScalarOrNAT = Union[str, libmissing.NAType]
5860

@@ -547,7 +549,7 @@ def _cmp_method(self, other, op):
547549
result = super()._cmp_method(other, op)
548550
return result.to_numpy(np.bool_, na_value=False)
549551

550-
def value_counts(self, dropna: bool = True):
552+
def value_counts(self, dropna: bool = True) -> Series:
551553
from pandas import Series
552554

553555
result = super().value_counts(dropna)

0 commit comments

Comments
 (0)