Skip to content

Commit 107250a

Browse files
iasoonyehoshuadimarsky
authored andcommitted
TYP: resolve mypy ignores in core/apply.py (pandas-dev#47066)
1 parent c751577 commit 107250a

File tree

1 file changed

+16
-19
lines changed

1 file changed

+16
-19
lines changed

pandas/core/apply.py

+16-19
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
AggObjType,
3333
Axis,
3434
NDFrameT,
35+
npt,
3536
)
3637
from pandas.errors import (
3738
DataError,
@@ -590,18 +591,17 @@ def normalize_dictlike_arg(
590591
cols_sorted = list(safe_sort(list(cols)))
591592
raise KeyError(f"Column(s) {cols_sorted} do not exist")
592593

593-
is_aggregator = lambda x: isinstance(x, (list, tuple, dict))
594+
aggregator_types = (list, tuple, dict)
594595

595596
# if we have a dict of any non-scalars
596597
# eg. {'A' : ['mean']}, normalize all to
597598
# be list-likes
598599
# Cannot use func.values() because arg may be a Series
599-
if any(is_aggregator(x) for _, x in func.items()):
600+
if any(isinstance(x, aggregator_types) for _, x in func.items()):
600601
new_func: AggFuncTypeDict = {}
601602
for k, v in func.items():
602-
if not is_aggregator(v):
603-
# mypy can't realize v is not a list here
604-
new_func[k] = [v] # type: ignore[list-item]
603+
if not isinstance(v, aggregator_types):
604+
new_func[k] = [v]
605605
else:
606606
new_func[k] = v
607607
func = new_func
@@ -1085,6 +1085,7 @@ def apply(self) -> DataFrame | Series:
10851085
# if we are a string, try to dispatch
10861086
return self.apply_str()
10871087

1088+
# self.f is Callable
10881089
return self.apply_standard()
10891090

10901091
def agg(self):
@@ -1122,7 +1123,8 @@ def apply_empty_result(self) -> Series:
11221123
)
11231124

11241125
def apply_standard(self) -> DataFrame | Series:
1125-
f = self.f
1126+
# caller is responsible for ensuring that f is Callable
1127+
f = cast(Callable, self.f)
11261128
obj = self.obj
11271129

11281130
with np.errstate(all="ignore"):
@@ -1135,14 +1137,9 @@ def apply_standard(self) -> DataFrame | Series:
11351137
mapped = obj._values.map(f)
11361138
else:
11371139
values = obj.astype(object)._values
1138-
# error: Argument 2 to "map_infer" has incompatible type
1139-
# "Union[Callable[..., Any], str, List[Union[Callable[..., Any], str]],
1140-
# Dict[Hashable, Union[Union[Callable[..., Any], str],
1141-
# List[Union[Callable[..., Any], str]]]]]"; expected
1142-
# "Callable[[Any], Any]"
11431140
mapped = lib.map_infer(
11441141
values,
1145-
f, # type: ignore[arg-type]
1142+
f,
11461143
convert=self.convert_dtype,
11471144
)
11481145

@@ -1211,7 +1208,7 @@ def transform(self):
12111208

12121209
def reconstruct_func(
12131210
func: AggFuncType | None, **kwargs
1214-
) -> tuple[bool, AggFuncType | None, list[str] | None, list[int] | None]:
1211+
) -> tuple[bool, AggFuncType | None, list[str] | None, npt.NDArray[np.intp] | None]:
12151212
"""
12161213
This is the internal function to reconstruct func given if there is relabeling
12171214
or not and also normalize the keyword to get new order of columns.
@@ -1238,7 +1235,7 @@ def reconstruct_func(
12381235
relabelling: bool, if there is relabelling or not
12391236
func: normalized and mangled func
12401237
columns: list of column names
1241-
order: list of columns indices
1238+
order: array of columns indices
12421239
12431240
Examples
12441241
--------
@@ -1250,7 +1247,7 @@ def reconstruct_func(
12501247
"""
12511248
relabeling = func is None and is_multi_agg_with_relabel(**kwargs)
12521249
columns: list[str] | None = None
1253-
order: list[int] | None = None
1250+
order: npt.NDArray[np.intp] | None = None
12541251

12551252
if not relabeling:
12561253
if isinstance(func, list) and len(func) > len(set(func)):
@@ -1297,7 +1294,9 @@ def is_multi_agg_with_relabel(**kwargs) -> bool:
12971294
)
12981295

12991296

1300-
def normalize_keyword_aggregation(kwargs: dict) -> tuple[dict, list[str], list[int]]:
1297+
def normalize_keyword_aggregation(
1298+
kwargs: dict,
1299+
) -> tuple[dict, list[str], npt.NDArray[np.intp]]:
13011300
"""
13021301
Normalize user-provided "named aggregation" kwargs.
13031302
Transforms from the new ``Mapping[str, NamedAgg]`` style kwargs
@@ -1351,9 +1350,7 @@ def normalize_keyword_aggregation(kwargs: dict) -> tuple[dict, list[str], list[i
13511350

13521351
# get the new index of columns by comparison
13531352
col_idx_order = Index(uniquified_aggspec).get_indexer(uniquified_order)
1354-
# error: Incompatible return value type (got "Tuple[defaultdict[Any, Any],
1355-
# Any, ndarray]", expected "Tuple[Dict[Any, Any], List[str], List[int]]")
1356-
return aggspec, columns, col_idx_order # type: ignore[return-value]
1353+
return aggspec, columns, col_idx_order
13571354

13581355

13591356
def _make_unique_kwarg_list(

0 commit comments

Comments
 (0)