Skip to content

Commit b0b1685

Browse files
authored
TYP: misc return values (#57108)
1 parent ab61a4c commit b0b1685

File tree

15 files changed

+84
-44
lines changed

15 files changed

+84
-44
lines changed

pandas/_config/config.py

+20-3
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,10 @@
6060
Any,
6161
Callable,
6262
Generic,
63+
Literal,
6364
NamedTuple,
6465
cast,
66+
overload,
6567
)
6668
import warnings
6769

@@ -740,7 +742,23 @@ def _build_option_description(k: str) -> str:
740742
return s
741743

742744

743-
def pp_options_list(keys: Iterable[str], width: int = 80, _print: bool = False):
745+
@overload
746+
def pp_options_list(
747+
keys: Iterable[str], *, width: int = ..., _print: Literal[False] = ...
748+
) -> str:
749+
...
750+
751+
752+
@overload
753+
def pp_options_list(
754+
keys: Iterable[str], *, width: int = ..., _print: Literal[True]
755+
) -> None:
756+
...
757+
758+
759+
def pp_options_list(
760+
keys: Iterable[str], *, width: int = 80, _print: bool = False
761+
) -> str | None:
744762
"""Builds a concise listing of available options, grouped by prefix"""
745763
from itertools import groupby
746764
from textwrap import wrap
@@ -770,8 +788,7 @@ def pp(name: str, ks: Iterable[str]) -> list[str]:
770788
s = "\n".join(ls)
771789
if _print:
772790
print(s)
773-
else:
774-
return s
791+
return s
775792

776793

777794
#

pandas/_libs/arrays.pyi

+10-10
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@ class NDArrayBacked:
1414
_ndarray: np.ndarray
1515
def __init__(self, values: np.ndarray, dtype: DtypeObj) -> None: ...
1616
@classmethod
17-
def _simple_new(cls, values: np.ndarray, dtype: DtypeObj): ...
18-
def _from_backing_data(self, values: np.ndarray): ...
19-
def __setstate__(self, state): ...
17+
def _simple_new(cls, values: np.ndarray, dtype: DtypeObj) -> Self: ...
18+
def _from_backing_data(self, values: np.ndarray) -> Self: ...
19+
def __setstate__(self, state) -> None: ...
2020
def __len__(self) -> int: ...
2121
@property
2222
def shape(self) -> Shape: ...
@@ -26,14 +26,14 @@ class NDArrayBacked:
2626
def size(self) -> int: ...
2727
@property
2828
def nbytes(self) -> int: ...
29-
def copy(self, order=...): ...
30-
def delete(self, loc, axis=...): ...
31-
def swapaxes(self, axis1, axis2): ...
32-
def repeat(self, repeats: int | Sequence[int], axis: int | None = ...): ...
33-
def reshape(self, *args, **kwargs): ...
34-
def ravel(self, order=...): ...
29+
def copy(self, order=...) -> Self: ...
30+
def delete(self, loc, axis=...) -> Self: ...
31+
def swapaxes(self, axis1, axis2) -> Self: ...
32+
def repeat(self, repeats: int | Sequence[int], axis: int | None = ...) -> Self: ...
33+
def reshape(self, *args, **kwargs) -> Self: ...
34+
def ravel(self, order=...) -> Self: ...
3535
@property
36-
def T(self): ...
36+
def T(self) -> Self: ...
3737
@classmethod
3838
def _concat_same_type(
3939
cls, to_concat: Sequence[Self], axis: AxisInt = ...

pandas/_libs/testing.pyi

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
def assert_dict_equal(a, b, compare_keys: bool = ...): ...
1+
from typing import Mapping
2+
3+
def assert_dict_equal(a: Mapping, b: Mapping, compare_keys: bool = ...) -> bool: ...
24
def assert_almost_equal(
35
a,
46
b,
@@ -9,4 +11,4 @@ def assert_almost_equal(
911
lobj=...,
1012
robj=...,
1113
index_values=...,
12-
): ...
14+
) -> bool: ...

pandas/_libs/tslibs/dtypes.pyi

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from enum import Enum
22

3+
from pandas._typing import Self
4+
35
OFFSET_TO_PERIOD_FREQSTR: dict[str, str]
46

57
def periods_per_day(reso: int = ...) -> int: ...
@@ -12,7 +14,7 @@ class PeriodDtypeBase:
1214
_n: int
1315

1416
# actually __cinit__
15-
def __new__(cls, code: int, n: int): ...
17+
def __new__(cls, code: int, n: int) -> Self: ...
1618
@property
1719
def _freq_group_code(self) -> int: ...
1820
@property

pandas/_libs/tslibs/offsets.pyi

+3-3
Original file line numberDiff line numberDiff line change
@@ -64,15 +64,15 @@ class BaseOffset:
6464
@overload
6565
def __rsub__(self, other: npt.NDArray[np.object_]) -> npt.NDArray[np.object_]: ...
6666
@overload
67-
def __rsub__(self, other: BaseOffset): ...
67+
def __rsub__(self, other: BaseOffset) -> Self: ...
6868
@overload
6969
def __rsub__(self, other: _DatetimeT) -> _DatetimeT: ...
7070
@overload
7171
def __rsub__(self, other: _TimedeltaT) -> _TimedeltaT: ...
7272
@overload
7373
def __mul__(self, other: np.ndarray) -> np.ndarray: ...
7474
@overload
75-
def __mul__(self, other: int): ...
75+
def __mul__(self, other: int) -> Self: ...
7676
@overload
7777
def __rmul__(self, other: np.ndarray) -> np.ndarray: ...
7878
@overload
@@ -100,7 +100,7 @@ def _get_offset(name: str) -> BaseOffset: ...
100100

101101
class SingleConstructorOffset(BaseOffset):
102102
@classmethod
103-
def _from_name(cls, suffix: None = ...): ...
103+
def _from_name(cls, suffix: None = ...) -> Self: ...
104104
def __reduce__(self): ...
105105

106106
@overload

pandas/_testing/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -482,7 +482,7 @@ def iat(x):
482482
_UNITS = ["s", "ms", "us", "ns"]
483483

484484

485-
def get_finest_unit(left: str, right: str):
485+
def get_finest_unit(left: str, right: str) -> str:
486486
"""
487487
Find the higher of two datetime64 units.
488488
"""

pandas/core/arrays/_mixins.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,9 @@ def method(self, *args, **kwargs):
8989
return cast(F, method)
9090

9191

92-
class NDArrayBackedExtensionArray(NDArrayBacked, ExtensionArray):
92+
# error: Definition of "delete/ravel/T/repeat/copy" in base class "NDArrayBacked"
93+
# is incompatible with definition in base class "ExtensionArray"
94+
class NDArrayBackedExtensionArray(NDArrayBacked, ExtensionArray): # type: ignore[misc]
9395
"""
9496
ExtensionArray that is backed by a single NumPy ndarray.
9597
"""
@@ -386,7 +388,7 @@ def fillna(
386388
# ------------------------------------------------------------------------
387389
# Reductions
388390

389-
def _wrap_reduction_result(self, axis: AxisInt | None, result):
391+
def _wrap_reduction_result(self, axis: AxisInt | None, result) -> Any:
390392
if axis is None or self.ndim == 1:
391393
return self._box_func(result)
392394
return self._from_backing_data(result)

pandas/core/arrays/base.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1781,7 +1781,7 @@ def _formatter(self, boxed: bool = False) -> Callable[[Any], str | None]:
17811781
# Reshaping
17821782
# ------------------------------------------------------------------------
17831783

1784-
def transpose(self, *axes: int) -> ExtensionArray:
1784+
def transpose(self, *axes: int) -> Self:
17851785
"""
17861786
Return a transposed view on this array.
17871787
@@ -1802,10 +1802,10 @@ def transpose(self, *axes: int) -> ExtensionArray:
18021802
return self[:]
18031803

18041804
@property
1805-
def T(self) -> ExtensionArray:
1805+
def T(self) -> Self:
18061806
return self.transpose()
18071807

1808-
def ravel(self, order: Literal["C", "F", "A", "K"] | None = "C") -> ExtensionArray:
1808+
def ravel(self, order: Literal["C", "F", "A", "K"] | None = "C") -> Self:
18091809
"""
18101810
Return a flattened view on this array.
18111811

pandas/core/arrays/categorical.py

+16-7
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,9 @@ def contains(cat, key, container) -> bool:
243243
return any(loc_ in container for loc_ in loc)
244244

245245

246-
class Categorical(NDArrayBackedExtensionArray, PandasObject, ObjectStringArrayMixin):
246+
# error: Definition of "delete/ravel/T/repeat/copy" in base class "NDArrayBacked"
247+
# is incompatible with definition in base class "ExtensionArray"
248+
class Categorical(NDArrayBackedExtensionArray, PandasObject, ObjectStringArrayMixin): # type: ignore[misc]
247249
"""
248250
Represent a categorical variable in classic R / S-plus fashion.
249251
@@ -561,6 +563,7 @@ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
561563
object is returned.
562564
"""
563565
dtype = pandas_dtype(dtype)
566+
result: Categorical | np.ndarray
564567
if self.dtype is dtype:
565568
result = self.copy() if copy else self
566569

@@ -1818,10 +1821,14 @@ def value_counts(self, dropna: bool = True) -> Series:
18181821
ix = np.append(ix, -1)
18191822

18201823
ix = coerce_indexer_dtype(ix, self.dtype.categories)
1821-
ix = self._from_backing_data(ix)
1824+
ix_categorical = self._from_backing_data(ix)
18221825

18231826
return Series(
1824-
count, index=CategoricalIndex(ix), dtype="int64", name="count", copy=False
1827+
count,
1828+
index=CategoricalIndex(ix_categorical),
1829+
dtype="int64",
1830+
name="count",
1831+
copy=False,
18251832
)
18261833

18271834
# error: Argument 2 of "_empty" is incompatible with supertype
@@ -2526,7 +2533,9 @@ def _concat_same_type(cls, to_concat: Sequence[Self], axis: AxisInt = 0) -> Self
25262533
result = res_flat.reshape(len(first), -1, order="F")
25272534
return result
25282535

2529-
result = union_categoricals(to_concat)
2536+
# error: Incompatible types in assignment (expression has type "Categorical",
2537+
# variable has type "Self")
2538+
result = union_categoricals(to_concat) # type: ignore[assignment]
25302539
return result
25312540

25322541
# ------------------------------------------------------------------
@@ -2666,11 +2675,11 @@ def _replace(self, *, to_replace, value, inplace: bool = False) -> Self | None:
26662675

26672676
new_categories = ser.take(locs)
26682677
new_categories = new_categories.drop_duplicates(keep="first")
2669-
new_categories = Index(new_categories)
2678+
index_categories = Index(new_categories)
26702679
new_codes = recode_for_categories(
2671-
cat._codes, all_values, new_categories, copy=False
2680+
cat._codes, all_values, index_categories, copy=False
26722681
)
2673-
new_dtype = CategoricalDtype(new_categories, ordered=self.dtype.ordered)
2682+
new_dtype = CategoricalDtype(index_categories, ordered=self.dtype.ordered)
26742683
NDArrayBacked.__init__(cat, new_codes, new_dtype)
26752684

26762685
if new_dtype != orig_dtype:

pandas/core/arrays/interval.py

+2
Original file line numberDiff line numberDiff line change
@@ -1727,6 +1727,8 @@ def insert(self, loc: int, item: Interval) -> Self:
17271727
return self._shallow_copy(new_left, new_right)
17281728

17291729
def delete(self, loc) -> Self:
1730+
new_left: np.ndarray | DatetimeArray | TimedeltaArray
1731+
new_right: np.ndarray | DatetimeArray | TimedeltaArray
17301732
if isinstance(self._left, np.ndarray):
17311733
new_left = np.delete(self._left, loc)
17321734
assert isinstance(self._right, np.ndarray)

pandas/core/arrays/string_.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -499,10 +499,10 @@ def astype(self, dtype, copy: bool = True):
499499
values = arr.astype(dtype.numpy_dtype)
500500
return IntegerArray(values, mask, copy=False)
501501
elif isinstance(dtype, FloatingDtype):
502-
arr = self.copy()
502+
arr_ea = self.copy()
503503
mask = self.isna()
504-
arr[mask] = "0"
505-
values = arr.astype(dtype.numpy_dtype)
504+
arr_ea[mask] = "0"
505+
values = arr_ea.astype(dtype.numpy_dtype)
506506
return FloatingArray(values, mask, copy=False)
507507
elif isinstance(dtype, ExtensionDtype):
508508
# Skip the NumpyExtensionArray.astype method

pandas/plotting/_core.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ def hist_series(
9898
9999
Returns
100100
-------
101-
matplotlib.Axes
101+
matplotlib.axes.Axes
102102
A histogram plot.
103103
104104
See Also

pandas/plotting/_matplotlib/core.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -1021,7 +1021,7 @@ def _col_idx_to_axis_idx(self, col_idx: int) -> int:
10211021
return col_idx
10221022

10231023
@final
1024-
def _get_ax(self, i: int):
1024+
def _get_ax(self, i: int) -> Axes:
10251025
# get the twinx ax if appropriate
10261026
if self.subplots:
10271027
i = self._col_idx_to_axis_idx(i)
@@ -1037,7 +1037,7 @@ def _get_ax(self, i: int):
10371037
return ax
10381038

10391039
@final
1040-
def on_right(self, i: int):
1040+
def on_right(self, i: int) -> bool:
10411041
if isinstance(self.secondary_y, bool):
10421042
return self.secondary_y
10431043

@@ -1210,7 +1210,7 @@ def _get_errorbars(
12101210
return errors
12111211

12121212
@final
1213-
def _get_subplots(self, fig: Figure):
1213+
def _get_subplots(self, fig: Figure) -> list[Axes]:
12141214
if Version(mpl.__version__) < Version("3.8"):
12151215
from matplotlib.axes import Subplot as Klass
12161216
else:
@@ -2100,9 +2100,11 @@ def blank_labeler(label, value):
21002100
results = ax.pie(y, labels=blabels, **kwds)
21012101

21022102
if kwds.get("autopct", None) is not None:
2103-
patches, texts, autotexts = results
2103+
# error: Need more than 2 values to unpack (3 expected)
2104+
patches, texts, autotexts = results # type: ignore[misc]
21042105
else:
2105-
patches, texts = results
2106+
# error: Too many values to unpack (2 expected, 3 provided)
2107+
patches, texts = results # type: ignore[misc]
21062108
autotexts = []
21072109

21082110
if self.fontsize is not None:

pandas/tseries/holiday.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -384,7 +384,7 @@ def register(cls) -> None:
384384
holiday_calendars[name] = cls
385385

386386

387-
def get_calendar(name: str):
387+
def get_calendar(name: str) -> AbstractHolidayCalendar:
388388
"""
389389
Return an instance of a calendar based on its name.
390390
@@ -433,7 +433,7 @@ def __init__(self, name: str = "", rules=None) -> None:
433433
if rules is not None:
434434
self.rules = rules
435435

436-
def rule_from_name(self, name: str):
436+
def rule_from_name(self, name: str) -> Holiday | None:
437437
for rule in self.rules:
438438
if rule.name == name:
439439
return rule

pandas/util/_doctools.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
if TYPE_CHECKING:
1010
from collections.abc import Iterable
1111

12+
from matplotlib.figure import Figure
13+
1214

1315
class TablePlotter:
1416
"""
@@ -46,7 +48,9 @@ def _get_cells(self, left, right, vertical) -> tuple[int, int]:
4648
hcells = sum([self._shape(df)[1] for df in left] + [self._shape(right)[1]])
4749
return hcells, vcells
4850

49-
def plot(self, left, right, labels: Iterable[str] = (), vertical: bool = True):
51+
def plot(
52+
self, left, right, labels: Iterable[str] = (), vertical: bool = True
53+
) -> Figure:
5054
"""
5155
Plot left / right DataFrames in specified layout.
5256

0 commit comments

Comments
 (0)