Skip to content

Commit f0a04c0

Browse files
Backport PR #42200 on branch 1.3.x (TYP: update for numpy-1.21.0) (#42205)
Co-authored-by: Simon Hawkins <[email protected]>
1 parent f461684 commit f0a04c0

File tree

23 files changed

+142
-111
lines changed

23 files changed

+142
-111
lines changed

pandas/core/apply.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1076,11 +1076,7 @@ def apply_standard(self) -> FrameOrSeriesUnion:
10761076

10771077
with np.errstate(all="ignore"):
10781078
if isinstance(f, np.ufunc):
1079-
# error: Argument 1 to "__call__" of "ufunc" has incompatible type
1080-
# "Series"; expected "Union[Union[int, float, complex, str, bytes,
1081-
# generic], Sequence[Union[int, float, complex, str, bytes, generic]],
1082-
# Sequence[Sequence[Any]], _SupportsArray]"
1083-
return f(obj) # type: ignore[arg-type]
1079+
return f(obj)
10841080

10851081
# row-wise access
10861082
if is_extension_array_dtype(obj.dtype) and hasattr(obj._values, "map"):

pandas/core/arrays/masked.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -409,9 +409,7 @@ def isin(self, values) -> BooleanArray: # type: ignore[override]
409409
result += self._mask
410410
else:
411411
result *= np.invert(self._mask)
412-
# error: No overload variant of "zeros_like" matches argument types
413-
# "BaseMaskedArray", "Type[bool]"
414-
mask = np.zeros_like(self, dtype=bool) # type: ignore[call-overload]
412+
mask = np.zeros_like(self, dtype=bool)
415413
return BooleanArray(result, mask, copy=False)
416414

417415
def copy(self: BaseMaskedArrayT) -> BaseMaskedArrayT:

pandas/core/arrays/period.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -341,7 +341,9 @@ def freq(self) -> BaseOffset:
341341
def __array__(self, dtype: NpDtype | None = None) -> np.ndarray:
342342
if dtype == "i8":
343343
return self.asi8
344-
elif dtype == bool:
344+
# error: Non-overlapping equality check (left operand type: "Optional[Union[str,
345+
# dtype[Any]]]", right operand type: "Type[bool]")
346+
elif dtype == bool: # type: ignore[comparison-overlap]
345347
return ~self._isnan
346348

347349
# This will raise TypeError for non-object dtypes

pandas/core/arrays/sparse/array.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1463,11 +1463,7 @@ def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):
14631463
return type(self)(result)
14641464

14651465
def __abs__(self):
1466-
# error: Argument 1 to "__call__" of "ufunc" has incompatible type
1467-
# "SparseArray"; expected "Union[Union[int, float, complex, str, bytes,
1468-
# generic], Sequence[Union[int, float, complex, str, bytes, generic]],
1469-
# Sequence[Sequence[Any]], _SupportsArray]"
1470-
return np.abs(self) # type: ignore[arg-type]
1466+
return np.abs(self)
14711467

14721468
# ------------------------------------------------------------------------
14731469
# Ops

pandas/core/common.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -410,7 +410,7 @@ def random_state(state=None):
410410
411411
Returns
412412
-------
413-
np.random.RandomState
413+
np.random.RandomState or np.random if state is None
414414
415415
"""
416416
if (

pandas/core/computation/pytables.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -226,11 +226,7 @@ def stringify(value):
226226
if v not in metadata:
227227
result = -1
228228
else:
229-
# error: Incompatible types in assignment (expression has type
230-
# "Union[Any, ndarray]", variable has type "int")
231-
result = metadata.searchsorted( # type: ignore[assignment]
232-
v, side="left"
233-
)
229+
result = metadata.searchsorted(v, side="left")
234230
return TermValue(result, result, "integer")
235231
elif kind == "integer":
236232
v = int(float(v))

pandas/core/dtypes/cast.py

Lines changed: 30 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
TYPE_CHECKING,
1616
Any,
1717
Sized,
18+
TypeVar,
1819
cast,
1920
overload,
2021
)
@@ -107,6 +108,8 @@
107108
_int32_max = np.iinfo(np.int32).max
108109
_int64_max = np.iinfo(np.int64).max
109110

111+
NumpyArrayT = TypeVar("NumpyArrayT", bound=np.ndarray)
112+
110113

111114
def maybe_convert_platform(
112115
values: list | tuple | range | np.ndarray | ExtensionArray,
@@ -659,7 +662,10 @@ def _ensure_dtype_type(value, dtype: np.dtype):
659662
object
660663
"""
661664
# Start with exceptions in which we do _not_ cast to numpy types
662-
if dtype == np.object_:
665+
666+
# error: Non-overlapping equality check (left operand type: "dtype[Any]", right
667+
# operand type: "Type[object_]")
668+
if dtype == np.object_: # type: ignore[comparison-overlap]
663669
return value
664670

665671
# Note: before we get here we have already excluded isna(value)
@@ -866,10 +872,10 @@ def maybe_infer_dtype_type(element):
866872

867873

868874
def maybe_upcast(
869-
values: np.ndarray,
875+
values: NumpyArrayT,
870876
fill_value: Scalar = np.nan,
871877
copy: bool = False,
872-
) -> tuple[np.ndarray, Scalar]:
878+
) -> tuple[NumpyArrayT, Scalar]:
873879
"""
874880
Provide explicit type promotion and coercion.
875881
@@ -1093,7 +1099,10 @@ def astype_nansafe(
10931099
raise ValueError("dtype must be np.dtype or ExtensionDtype")
10941100

10951101
if arr.dtype.kind in ["m", "M"] and (
1096-
issubclass(dtype.type, str) or dtype == object
1102+
issubclass(dtype.type, str)
1103+
# error: Non-overlapping equality check (left operand type: "dtype[Any]", right
1104+
# operand type: "Type[object]")
1105+
or dtype == object # type: ignore[comparison-overlap]
10971106
):
10981107
from pandas.core.construction import ensure_wrapped_if_datetimelike
10991108

@@ -1104,7 +1113,9 @@ def astype_nansafe(
11041113
return lib.ensure_string_array(arr, skipna=skipna, convert_na_value=False)
11051114

11061115
elif is_datetime64_dtype(arr):
1107-
if dtype == np.int64:
1116+
# Non-overlapping equality check (left operand type: "dtype[Any]", right
1117+
# operand type: "Type[signedinteger[Any]]")
1118+
if dtype == np.int64: # type: ignore[comparison-overlap]
11081119
warnings.warn(
11091120
f"casting {arr.dtype} values to int64 with .astype(...) "
11101121
"is deprecated and will raise in a future version. "
@@ -1124,7 +1135,9 @@ def astype_nansafe(
11241135
raise TypeError(f"cannot astype a datetimelike from [{arr.dtype}] to [{dtype}]")
11251136

11261137
elif is_timedelta64_dtype(arr):
1127-
if dtype == np.int64:
1138+
# error: Non-overlapping equality check (left operand type: "dtype[Any]", right
1139+
# operand type: "Type[signedinteger[Any]]")
1140+
if dtype == np.int64: # type: ignore[comparison-overlap]
11281141
warnings.warn(
11291142
f"casting {arr.dtype} values to int64 with .astype(...) "
11301143
"is deprecated and will raise in a future version. "
@@ -1398,10 +1411,9 @@ def convert_dtypes(
13981411

13991412
if is_string_dtype(inferred_dtype):
14001413
if not convert_string:
1401-
inferred_dtype = input_array.dtype
1414+
return input_array.dtype
14021415
else:
1403-
inferred_dtype = pandas_dtype("string")
1404-
return inferred_dtype
1416+
return pandas_dtype("string")
14051417

14061418
if convert_integer:
14071419
target_int_dtype = pandas_dtype("Int64")
@@ -1454,7 +1466,9 @@ def convert_dtypes(
14541466
else:
14551467
return input_array.dtype
14561468

1457-
return inferred_dtype
1469+
# error: Incompatible return value type (got "Union[str, Union[dtype[Any],
1470+
# ExtensionDtype]]", expected "Union[dtype[Any], ExtensionDtype]")
1471+
return inferred_dtype # type: ignore[return-value]
14581472

14591473

14601474
def maybe_infer_to_datetimelike(
@@ -1831,7 +1845,9 @@ def construct_2d_arraylike_from_scalar(
18311845

18321846
if dtype.kind in ["m", "M"]:
18331847
value = maybe_unbox_datetimelike_tz_deprecation(value, dtype, stacklevel=4)
1834-
elif dtype == object:
1848+
# error: Non-overlapping equality check (left operand type: "dtype[Any]", right
1849+
# operand type: "Type[object]")
1850+
elif dtype == object: # type: ignore[comparison-overlap]
18351851
if isinstance(value, (np.timedelta64, np.datetime64)):
18361852
# calling np.array below would cast to pytimedelta/pydatetime
18371853
out = np.empty(shape, dtype=object)
@@ -2206,7 +2222,9 @@ def can_hold_element(arr: ArrayLike, element: Any) -> bool:
22062222
return tipo.kind == "b"
22072223
return lib.is_bool(element)
22082224

2209-
elif dtype == object:
2225+
# error: Non-overlapping equality check (left operand type: "dtype[Any]", right
2226+
# operand type: "Type[object]")
2227+
elif dtype == object: # type: ignore[comparison-overlap]
22102228
return True
22112229

22122230
elif dtype.kind == "S":

pandas/core/frame.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -648,7 +648,7 @@ def __init__(
648648
elif isinstance(data, (np.ndarray, Series, Index)):
649649
if data.dtype.names:
650650
# i.e. numpy structured array
651-
651+
data = cast(np.ndarray, data)
652652
mgr = rec_array_to_mgr(
653653
data,
654654
index,
@@ -2280,9 +2280,7 @@ def to_records(
22802280
if dtype_mapping is None:
22812281
formats.append(v.dtype)
22822282
elif isinstance(dtype_mapping, (type, np.dtype, str)):
2283-
# error: Argument 1 to "append" of "list" has incompatible type
2284-
# "Union[type, dtype, str]"; expected "dtype"
2285-
formats.append(dtype_mapping) # type: ignore[arg-type]
2283+
formats.append(dtype_mapping)
22862284
else:
22872285
element = "row" if i < index_len else "column"
22882286
msg = f"Invalid dtype {dtype_mapping} specified for {element} {name}"

pandas/core/generic.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9751,11 +9751,9 @@ def abs(self: FrameOrSeries) -> FrameOrSeries:
97519751
2 6 30 -30
97529752
3 7 40 -50
97539753
"""
9754-
# error: Argument 1 to "__call__" of "ufunc" has incompatible type
9755-
# "FrameOrSeries"; expected "Union[Union[int, float, complex, str, bytes,
9756-
# generic], Sequence[Union[int, float, complex, str, bytes, generic]],
9757-
# Sequence[Sequence[Any]], _SupportsArray]"
9758-
return np.abs(self) # type: ignore[arg-type]
9754+
# error: Incompatible return value type (got "ndarray[Any, dtype[Any]]",
9755+
# expected "FrameOrSeries")
9756+
return np.abs(self) # type: ignore[return-value]
97599757

97609758
@final
97619759
def describe(

pandas/core/groupby/ops.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,9 @@ def _get_cython_function(
161161
f = getattr(libgroupby, ftype)
162162
if is_numeric:
163163
return f
164-
elif dtype == object:
164+
# error: Non-overlapping equality check (left operand type: "dtype[Any]", right
165+
# operand type: "Literal['object']")
166+
elif dtype == object: # type: ignore[comparison-overlap]
165167
if "object" not in f.__signatures__:
166168
# raise NotImplementedError here rather than TypeError later
167169
raise NotImplementedError(

pandas/core/indexes/base.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -559,7 +559,9 @@ def _dtype_to_subclass(cls, dtype: DtypeObj):
559559

560560
return Int64Index
561561

562-
elif dtype == object:
562+
# error: Non-overlapping equality check (left operand type: "dtype[Any]", right
563+
# operand type: "Type[object]")
564+
elif dtype == object: # type: ignore[comparison-overlap]
563565
# NB: assuming away MultiIndex
564566
return Index
565567

pandas/core/indexes/category.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -193,17 +193,12 @@ def _can_hold_strings(self):
193193
def _engine_type(self):
194194
# self.codes can have dtype int8, int16, int32 or int64, so we need
195195
# to return the corresponding engine type (libindex.Int8Engine, etc.).
196-
197-
# error: Invalid index type "Type[generic]" for "Dict[Type[signedinteger[Any]],
198-
# Any]"; expected type "Type[signedinteger[Any]]"
199196
return {
200197
np.int8: libindex.Int8Engine,
201198
np.int16: libindex.Int16Engine,
202199
np.int32: libindex.Int32Engine,
203200
np.int64: libindex.Int64Engine,
204-
}[
205-
self.codes.dtype.type # type: ignore[index]
206-
]
201+
}[self.codes.dtype.type]
207202

208203
_attributes = ["name"]
209204

pandas/core/indexes/extension.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -397,11 +397,13 @@ def astype(self, dtype, copy: bool = True) -> Index:
397397
return self
398398
return self.copy()
399399

400+
# error: Non-overlapping equality check (left operand type: "dtype[Any]", right
401+
# operand type: "Literal['M8[ns]']")
400402
if (
401403
isinstance(self.dtype, np.dtype)
402404
and isinstance(dtype, np.dtype)
403405
and dtype.kind == "M"
404-
and dtype != "M8[ns]"
406+
and dtype != "M8[ns]" # type: ignore[comparison-overlap]
405407
):
406408
# For now Datetime supports this by unwrapping ndarray, but DTI doesn't
407409
raise TypeError(f"Cannot cast {type(self).__name__} to dtype")

pandas/core/internals/blocks.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1167,13 +1167,17 @@ def shift(self, periods: int, axis: int = 0, fill_value: Any = None) -> list[Blo
11671167
# convert integer to float if necessary. need to do a lot more than
11681168
# that, handle boolean etc also
11691169

1170-
# error: Argument 1 to "maybe_upcast" has incompatible type "Union[ndarray,
1171-
# ExtensionArray]"; expected "ndarray"
1170+
# error: Value of type variable "NumpyArrayT" of "maybe_upcast" cannot be
1171+
# "Union[ndarray[Any, Any], ExtensionArray]"
11721172
new_values, fill_value = maybe_upcast(
1173-
self.values, fill_value # type: ignore[arg-type]
1173+
self.values, fill_value # type: ignore[type-var]
11741174
)
11751175

1176-
new_values = shift(new_values, periods, axis, fill_value)
1176+
# error: Argument 1 to "shift" has incompatible type "Union[ndarray[Any, Any],
1177+
# ExtensionArray]"; expected "ndarray[Any, Any]"
1178+
new_values = shift(
1179+
new_values, periods, axis, fill_value # type: ignore[arg-type]
1180+
)
11771181

11781182
return [self.make_block(new_values)]
11791183

@@ -1894,9 +1898,7 @@ def get_block_type(values, dtype: Dtype | None = None):
18941898
cls = ExtensionBlock
18951899
elif isinstance(dtype, CategoricalDtype):
18961900
cls = CategoricalBlock
1897-
# error: Non-overlapping identity check (left operand type: "Type[generic]",
1898-
# right operand type: "Type[Timestamp]")
1899-
elif vtype is Timestamp: # type: ignore[comparison-overlap]
1901+
elif vtype is Timestamp:
19001902
cls = DatetimeTZBlock
19011903
elif isinstance(dtype, ExtensionDtype):
19021904
# Note: need to be sure PandasArray is unwrapped before we get here

pandas/core/internals/construction.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
Any,
1111
Hashable,
1212
Sequence,
13+
cast,
1314
)
1415
import warnings
1516

@@ -165,6 +166,9 @@ def rec_array_to_mgr(
165166

166167
# fill if needed
167168
if isinstance(data, np.ma.MaskedArray):
169+
# GH#42200 we only get here with MaskedRecords, but check for the
170+
# parent class MaskedArray to avoid the need to import MaskedRecords
171+
data = cast("MaskedRecords", data)
168172
new_arrays = fill_masked_arrays(data, arr_columns)
169173
else:
170174
# error: Incompatible types in assignment (expression has type

0 commit comments

Comments
 (0)