Skip to content

Commit 1cc40fa

Browse files
authored
TYP: fix type-ignores in core (#40423)
1 parent 454194e commit 1cc40fa

20 files changed

+62
-119
lines changed

pandas/core/algorithms.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1867,7 +1867,7 @@ def _sort_mixed(values):
18671867
return np.concatenate([nums, np.asarray(strs, dtype=object)])
18681868

18691869

1870-
def _sort_tuples(values: np.ndarray):
1870+
def _sort_tuples(values: np.ndarray) -> np.ndarray:
18711871
"""
18721872
Convert array of tuples (1d) to array or array (2d).
18731873
We need to keep the columns separately as they contain different types and

pandas/core/arraylike.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,7 @@
55
ExtensionArray
66
"""
77
import operator
8-
from typing import (
9-
Any,
10-
Callable,
11-
)
8+
from typing import Any
129
import warnings
1310

1411
import numpy as np
@@ -172,7 +169,7 @@ def _is_aligned(frame, other):
172169
return frame.columns.equals(other.index)
173170

174171

175-
def _maybe_fallback(ufunc: Callable, method: str, *inputs: Any, **kwargs: Any):
172+
def _maybe_fallback(ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any):
176173
"""
177174
In the future DataFrame, inputs to ufuncs will be aligned before applying
178175
the ufunc, but for now we ignore the index but raise a warning if behaviour

pandas/core/arrays/boolean.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -331,7 +331,7 @@ def map_string(s):
331331

332332
_HANDLED_TYPES = (np.ndarray, numbers.Number, bool, np.bool_)
333333

334-
def __array_ufunc__(self, ufunc, method: str, *inputs, **kwargs):
334+
def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):
335335
# For BooleanArray inputs, we apply the ufunc to ._data
336336
# and mask the result.
337337
if method == "reduce":

pandas/core/arrays/categorical.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1388,7 +1388,7 @@ def __array__(self, dtype: Optional[NpDtype] = None) -> np.ndarray:
13881388
# ndarray.
13891389
return np.asarray(ret)
13901390

1391-
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
1391+
def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):
13921392
# for binary ops, use our custom dunder methods
13931393
result = ops.maybe_dispatch_ufunc_to_dunder_op(
13941394
self, ufunc, method, *inputs, **kwargs
@@ -2429,7 +2429,7 @@ def replace(self, to_replace, value, inplace: bool = False):
24292429

24302430
# ------------------------------------------------------------------------
24312431
# String methods interface
2432-
def _str_map(self, f, na_value=np.nan, dtype=np.dtype(object)):
2432+
def _str_map(self, f, na_value=np.nan, dtype=np.dtype("object")):
24332433
# Optimization to apply the callable `f` to the categories once
24342434
# and rebuild the result by `take`ing from the result with the codes.
24352435
# Returns the same type as the object-dtype implementation though.

pandas/core/arrays/numeric.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ def _arith_method(self, other, op):
152152

153153
_HANDLED_TYPES = (np.ndarray, numbers.Number)
154154

155-
def __array_ufunc__(self, ufunc, method: str, *inputs, **kwargs):
155+
def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):
156156
# For NumericArray inputs, we apply the ufunc to ._data
157157
# and mask the result.
158158
if method == "reduce":

pandas/core/arrays/numpy_.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ def __array__(self, dtype: Optional[NpDtype] = None) -> np.ndarray:
137137

138138
_HANDLED_TYPES = (np.ndarray, numbers.Number)
139139

140-
def __array_ufunc__(self, ufunc, method: str, *inputs, **kwargs):
140+
def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):
141141
# Lightly modified version of
142142
# https://numpy.org/doc/stable/reference/generated/numpy.lib.mixins.NDArrayOperatorsMixin.html
143143
# The primary modification is not boxing scalar return values

pandas/core/arrays/sparse/array.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1396,7 +1396,7 @@ def mean(self, axis=0, *args, **kwargs):
13961396

13971397
_HANDLED_TYPES = (np.ndarray, numbers.Number)
13981398

1399-
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
1399+
def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):
14001400
out = kwargs.get("out", ())
14011401

14021402
for x in inputs + out:

pandas/core/base.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
Dtype,
2424
DtypeObj,
2525
IndexLabel,
26+
Shape,
2627
)
2728
from pandas.compat import PYPY
2829
from pandas.compat.numpy import function as nv
@@ -389,7 +390,7 @@ def transpose(self: _T, *args, **kwargs) -> _T:
389390
)
390391

391392
@property
392-
def shape(self):
393+
def shape(self) -> Shape:
393394
"""
394395
Return a tuple of the shape of the underlying data.
395396
"""
@@ -511,7 +512,7 @@ def to_numpy(
511512
copy: bool = False,
512513
na_value=lib.no_default,
513514
**kwargs,
514-
):
515+
) -> np.ndarray:
515516
"""
516517
A NumPy ndarray representing the values in this Series or Index.
517518
@@ -852,7 +853,7 @@ def __iter__(self):
852853
return map(self._values.item, range(self._values.size))
853854

854855
@cache_readonly
855-
def hasnans(self):
856+
def hasnans(self) -> bool:
856857
"""
857858
Return if I have any nans; enables various perf speedups.
858859
"""

pandas/core/dtypes/cast.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -689,15 +689,14 @@ def _maybe_promote(dtype: np.dtype, fill_value=np.nan):
689689
if fv.tz is None:
690690
return dtype, fv.asm8
691691

692-
# error: Value of type variable "_DTypeScalar" of "dtype" cannot be "object"
693-
return np.dtype(object), fill_value # type: ignore[type-var]
692+
return np.dtype("object"), fill_value
694693

695694
elif issubclass(dtype.type, np.timedelta64):
696695
inferred, fv = infer_dtype_from_scalar(fill_value, pandas_dtype=True)
697696
if inferred == dtype:
698697
return dtype, fv
699-
# error: Value of type variable "_DTypeScalar" of "dtype" cannot be "object"
700-
return np.dtype(object), fill_value # type: ignore[type-var]
698+
699+
return np.dtype("object"), fill_value
701700

702701
elif is_float(fill_value):
703702
if issubclass(dtype.type, np.bool_):

pandas/core/dtypes/missing.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -648,8 +648,7 @@ def is_valid_na_for_dtype(obj, dtype: DtypeObj) -> bool:
648648
# Numeric
649649
return obj is not NaT and not isinstance(obj, (np.datetime64, np.timedelta64))
650650

651-
# error: Value of type variable "_DTypeScalar" of "dtype" cannot be "object"
652-
elif dtype == np.dtype(object): # type: ignore[type-var]
651+
elif dtype == np.dtype("object"):
653652
# This is needed for Categorical, but is kind of weird
654653
return True
655654

pandas/core/frame.py

+14-53
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@
123123
is_sequence,
124124
pandas_dtype,
125125
)
126+
from pandas.core.dtypes.dtypes import ExtensionDtype
126127
from pandas.core.dtypes.missing import (
127128
isna,
128129
notna,
@@ -584,25 +585,17 @@ def __init__(
584585
)
585586

586587
elif isinstance(data, dict):
587-
# error: Argument "dtype" to "dict_to_mgr" has incompatible type
588-
# "Union[ExtensionDtype, str, dtype[Any], Type[object], None]"; expected
589-
# "Union[dtype[Any], ExtensionDtype, None]"
590-
mgr = dict_to_mgr(
591-
data, index, columns, dtype=dtype, typ=manager # type: ignore[arg-type]
592-
)
588+
mgr = dict_to_mgr(data, index, columns, dtype=dtype, typ=manager)
593589
elif isinstance(data, ma.MaskedArray):
594590
import numpy.ma.mrecords as mrecords
595591

596592
# masked recarray
597593
if isinstance(data, mrecords.MaskedRecords):
598-
# error: Argument 4 to "rec_array_to_mgr" has incompatible type
599-
# "Union[ExtensionDtype, str, dtype[Any], Type[object], None]"; expected
600-
# "Union[dtype[Any], ExtensionDtype, None]"
601594
mgr = rec_array_to_mgr(
602595
data,
603596
index,
604597
columns,
605-
dtype, # type: ignore[arg-type]
598+
dtype,
606599
copy,
607600
typ=manager,
608601
)
@@ -611,13 +604,10 @@ def __init__(
611604
else:
612605
data = sanitize_masked_array(data)
613606
mgr = ndarray_to_mgr(
614-
# error: Argument "dtype" to "ndarray_to_mgr" has incompatible type
615-
# "Union[ExtensionDtype, str, dtype[Any], Type[object], None]";
616-
# expected "Union[dtype[Any], ExtensionDtype, None]"
617607
data,
618608
index,
619609
columns,
620-
dtype=dtype, # type: ignore[arg-type]
610+
dtype=dtype,
621611
copy=copy,
622612
typ=manager,
623613
)
@@ -626,14 +616,11 @@ def __init__(
626616
if data.dtype.names:
627617
# i.e. numpy structured array
628618

629-
# error: Argument 4 to "rec_array_to_mgr" has incompatible type
630-
# "Union[ExtensionDtype, str, dtype[Any], Type[object], None]"; expected
631-
# "Union[dtype[Any], ExtensionDtype, None]"
632619
mgr = rec_array_to_mgr(
633620
data,
634621
index,
635622
columns,
636-
dtype, # type: ignore[arg-type]
623+
dtype,
637624
copy,
638625
typ=manager,
639626
)
@@ -642,24 +629,18 @@ def __init__(
642629
mgr = dict_to_mgr(
643630
# error: Item "ndarray" of "Union[ndarray, Series, Index]" has no
644631
# attribute "name"
645-
# error: Argument "dtype" to "dict_to_mgr" has incompatible type
646-
# "Union[ExtensionDtype, str, dtype[Any], Type[object], None]";
647-
# expected "Union[dtype[Any], ExtensionDtype, None]"
648632
{data.name: data}, # type: ignore[union-attr]
649633
index,
650634
columns,
651-
dtype=dtype, # type: ignore[arg-type]
635+
dtype=dtype,
652636
typ=manager,
653637
)
654638
else:
655639
mgr = ndarray_to_mgr(
656-
# error: Argument "dtype" to "ndarray_to_mgr" has incompatible type
657-
# "Union[ExtensionDtype, str, dtype[Any], Type[object], None]";
658-
# expected "Union[dtype[Any], ExtensionDtype, None]"
659640
data,
660641
index,
661642
columns,
662-
dtype=dtype, # type: ignore[arg-type]
643+
dtype=dtype,
663644
copy=copy,
664645
typ=manager,
665646
)
@@ -680,46 +661,34 @@ def __init__(
680661
arrays, columns, index = nested_data_to_arrays(
681662
# error: Argument 3 to "nested_data_to_arrays" has incompatible
682663
# type "Optional[Collection[Any]]"; expected "Optional[Index]"
683-
# error: Argument 4 to "nested_data_to_arrays" has incompatible
684-
# type "Union[ExtensionDtype, str, dtype[Any], Type[object],
685-
# None]"; expected "Union[dtype[Any], ExtensionDtype, None]"
686664
data,
687665
columns,
688666
index, # type: ignore[arg-type]
689-
dtype, # type: ignore[arg-type]
667+
dtype,
690668
)
691669
mgr = arrays_to_mgr(
692-
# error: Argument "dtype" to "arrays_to_mgr" has incompatible
693-
# type "Union[ExtensionDtype, str, dtype[Any], Type[object],
694-
# None]"; expected "Union[dtype[Any], ExtensionDtype, None]"
695670
arrays,
696671
columns,
697672
index,
698673
columns,
699-
dtype=dtype, # type: ignore[arg-type]
674+
dtype=dtype,
700675
typ=manager,
701676
)
702677
else:
703678
mgr = ndarray_to_mgr(
704-
# error: Argument "dtype" to "ndarray_to_mgr" has incompatible
705-
# type "Union[ExtensionDtype, str, dtype[Any], Type[object],
706-
# None]"; expected "Union[dtype[Any], ExtensionDtype, None]"
707679
data,
708680
index,
709681
columns,
710-
dtype=dtype, # type: ignore[arg-type]
682+
dtype=dtype,
711683
copy=copy,
712684
typ=manager,
713685
)
714686
else:
715-
# error: Argument "dtype" to "dict_to_mgr" has incompatible type
716-
# "Union[ExtensionDtype, str, dtype[Any], Type[object], None]"; expected
717-
# "Union[dtype[Any], ExtensionDtype, None]"
718687
mgr = dict_to_mgr(
719688
{},
720689
index,
721690
columns,
722-
dtype=dtype, # type: ignore[arg-type]
691+
dtype=dtype,
723692
typ=manager,
724693
)
725694
# For data is scalar
@@ -731,16 +700,11 @@ def __init__(
731700
dtype, _ = infer_dtype_from_scalar(data, pandas_dtype=True)
732701

733702
# For data is a scalar extension dtype
734-
if is_extension_array_dtype(dtype):
703+
if isinstance(dtype, ExtensionDtype):
735704
# TODO(EA2D): special case not needed with 2D EAs
736705

737706
values = [
738-
# error: Argument 3 to "construct_1d_arraylike_from_scalar"
739-
# has incompatible type "Union[ExtensionDtype, str, dtype,
740-
# Type[object]]"; expected "Union[dtype, ExtensionDtype]"
741-
construct_1d_arraylike_from_scalar(
742-
data, len(index), dtype # type: ignore[arg-type]
743-
)
707+
construct_1d_arraylike_from_scalar(data, len(index), dtype)
744708
for _ in range(len(columns))
745709
]
746710
mgr = arrays_to_mgr(
@@ -750,13 +714,10 @@ def __init__(
750714
# error: Incompatible types in assignment (expression has type
751715
# "ndarray", variable has type "List[ExtensionArray]")
752716
values = construct_2d_arraylike_from_scalar( # type: ignore[assignment]
753-
# error: Argument 4 to "construct_2d_arraylike_from_scalar" has
754-
# incompatible type "Union[ExtensionDtype, str, dtype[Any],
755-
# Type[object]]"; expected "dtype[Any]"
756717
data,
757718
len(index),
758719
len(columns),
759-
dtype, # type: ignore[arg-type]
720+
dtype,
760721
copy,
761722
)
762723

pandas/core/generic.py

+7-17
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
CompressionOptions,
4545
Dtype,
4646
DtypeArg,
47+
DtypeObj,
4748
FilePathOrBuffer,
4849
FrameOrSeries,
4950
IndexKeyFunc,
@@ -411,7 +412,7 @@ def set_flags(
411412

412413
@final
413414
@classmethod
414-
def _validate_dtype(cls, dtype):
415+
def _validate_dtype(cls, dtype) -> Optional[DtypeObj]:
415416
""" validate the passed dtype """
416417
if dtype is not None:
417418
dtype = pandas_dtype(dtype)
@@ -1995,13 +1996,9 @@ def __array_wrap__(
19951996
)
19961997

19971998
def __array_ufunc__(
1998-
self, ufunc: Callable, method: str, *inputs: Any, **kwargs: Any
1999+
self, ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any
19992000
):
2000-
# error: Argument 2 to "array_ufunc" has incompatible type "Callable[..., Any]";
2001-
# expected "ufunc"
2002-
return arraylike.array_ufunc(
2003-
self, ufunc, method, *inputs, **kwargs # type: ignore[arg-type]
2004-
)
2001+
return arraylike.array_ufunc(self, ufunc, method, *inputs, **kwargs)
20052002

20062003
# ideally we would define this to avoid the getattr checks, but
20072004
# is slower
@@ -4900,7 +4897,6 @@ def _reindex_axes(
49004897

49014898
return obj
49024899

4903-
@final
49044900
def _needs_reindex_multi(self, axes, method, level) -> bool_t:
49054901
"""Check if we do need a multi reindex."""
49064902
return (
@@ -6998,10 +6994,7 @@ def interpolate(
69986994
f"`limit_direction` must be 'backward' for method `{method}`"
69996995
)
70006996

7001-
# error: Value of type variable "_DTypeScalar" of "dtype" cannot be "object"
7002-
if obj.ndim == 2 and np.all(
7003-
obj.dtypes == np.dtype(object) # type: ignore[type-var]
7004-
):
6997+
if obj.ndim == 2 and np.all(obj.dtypes == np.dtype("object")):
70056998
raise TypeError(
70066999
"Cannot interpolate with all object-dtype columns "
70077000
"in the DataFrame. Try setting at least one "
@@ -8488,15 +8481,12 @@ def ranker(data):
84888481
na_option=na_option,
84898482
pct=pct,
84908483
)
8491-
# error: Incompatible types in assignment (expression has type
8492-
# "FrameOrSeries", variable has type "ndarray")
84938484
# error: Argument 1 to "NDFrame" has incompatible type "ndarray"; expected
84948485
# "Union[ArrayManager, BlockManager]"
8495-
ranks = self._constructor( # type: ignore[assignment]
8486+
ranks_obj = self._constructor(
84968487
ranks, **data._construct_axes_dict() # type: ignore[arg-type]
84978488
)
8498-
# error: "ndarray" has no attribute "__finalize__"
8499-
return ranks.__finalize__(self, method="rank") # type: ignore[attr-defined]
8489+
return ranks_obj.__finalize__(self, method="rank")
85008490

85018491
# if numeric_only is None, and we can't get anything, we try with
85028492
# numeric_only=True

0 commit comments

Comments
 (0)