Skip to content

TYP: update for numpy-1.21.0 #42200

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions pandas/core/apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -1076,11 +1076,7 @@ def apply_standard(self) -> FrameOrSeriesUnion:

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

# row-wise access
if is_extension_array_dtype(obj.dtype) and hasattr(obj._values, "map"):
Expand Down
4 changes: 1 addition & 3 deletions pandas/core/arrays/masked.py
Original file line number Diff line number Diff line change
Expand Up @@ -409,9 +409,7 @@ def isin(self, values) -> BooleanArray: # type: ignore[override]
result += self._mask
else:
result *= np.invert(self._mask)
# error: No overload variant of "zeros_like" matches argument types
# "BaseMaskedArray", "Type[bool]"
mask = np.zeros_like(self, dtype=bool) # type: ignore[call-overload]
mask = np.zeros_like(self, dtype=bool)
return BooleanArray(result, mask, copy=False)

def copy(self: BaseMaskedArrayT) -> BaseMaskedArrayT:
Expand Down
4 changes: 3 additions & 1 deletion pandas/core/arrays/period.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,9 @@ def freq(self) -> BaseOffset:
def __array__(self, dtype: NpDtype | None = None) -> np.ndarray:
if dtype == "i8":
return self.asi8
elif dtype == bool:
# error: Non-overlapping equality check (left operand type: "Optional[Union[str,
# dtype[Any]]]", right operand type: "Type[bool]")
elif dtype == bool: # type: ignore[comparison-overlap]
return ~self._isnan

# This will raise TypeError for non-object dtypes
Expand Down
6 changes: 1 addition & 5 deletions pandas/core/arrays/sparse/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -1463,11 +1463,7 @@ def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):
return type(self)(result)

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

# ------------------------------------------------------------------------
# Ops
Expand Down
19 changes: 16 additions & 3 deletions pandas/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,19 +411,32 @@ def random_state(state: RandomState | None = None) -> np.random.RandomState:

Returns
-------
np.random.RandomState
np.random.RandomState or np.random if state is None

"""
if (
is_integer(state)
or is_array_like(state)
or (not np_version_under1p18 and isinstance(state, np.random.BitGenerator))
):
return np.random.RandomState(state)
# error: Argument 1 to "RandomState" has incompatible type "Optional[Union[int,
# Union[ExtensionArray, ndarray[Any, Any]], Generator, RandomState]]"; expected
# "Union[None, Union[Union[_SupportsArray[dtype[Union[bool_, integer[Any]]]],
# Sequence[_SupportsArray[dtype[Union[bool_, integer[Any]]]]],
# Sequence[Sequence[_SupportsArray[dtype[Union[bool_, integer[Any]]]]]],
# Sequence[Sequence[Sequence[_SupportsArray[dtype[Union[bool_,
# integer[Any]]]]]]],
# Sequence[Sequence[Sequence[Sequence[_SupportsArray[dtype[Union[bool_,
# integer[Any]]]]]]]]], Union[bool, int, Sequence[Union[bool, int]],
# Sequence[Sequence[Union[bool, int]]], Sequence[Sequence[Sequence[Union[bool,
# int]]]], Sequence[Sequence[Sequence[Sequence[Union[bool, int]]]]]]],
# BitGenerator]"
return np.random.RandomState(state) # type: ignore[arg-type]
elif isinstance(state, np.random.RandomState):
return state
elif state is None:
return np.random
# error: Incompatible return value type (got Module, expected "RandomState")
return np.random # type: ignore[return-value]
else:
raise ValueError(
"random_state must be an integer, array-like, a BitGenerator, "
Expand Down
6 changes: 1 addition & 5 deletions pandas/core/computation/pytables.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,11 +226,7 @@ def stringify(value):
if v not in metadata:
result = -1
else:
# error: Incompatible types in assignment (expression has type
# "Union[Any, ndarray]", variable has type "int")
result = metadata.searchsorted( # type: ignore[assignment]
v, side="left"
)
result = metadata.searchsorted(v, side="left")
return TermValue(result, result, "integer")
elif kind == "integer":
v = int(float(v))
Expand Down
42 changes: 30 additions & 12 deletions pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
TYPE_CHECKING,
Any,
Sized,
TypeVar,
cast,
overload,
)
Expand Down Expand Up @@ -107,6 +108,8 @@
_int32_max = np.iinfo(np.int32).max
_int64_max = np.iinfo(np.int64).max

NumpyArrayT = TypeVar("NumpyArrayT", bound=np.ndarray)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why can't we just use np.ndarray?



def maybe_convert_platform(
values: list | tuple | range | np.ndarray | ExtensionArray,
Expand Down Expand Up @@ -659,7 +662,10 @@ def _ensure_dtype_type(value, dtype: np.dtype):
object
"""
# Start with exceptions in which we do _not_ cast to numpy types
if dtype == np.object_:

# error: Non-overlapping equality check (left operand type: "dtype[Any]", right
# operand type: "Type[object_]")
if dtype == np.object_: # type: ignore[comparison-overlap]
return value

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


def maybe_upcast(
values: np.ndarray,
values: NumpyArrayT,
fill_value: Scalar = np.nan,
copy: bool = False,
) -> tuple[np.ndarray, Scalar]:
) -> tuple[NumpyArrayT, Scalar]:
"""
Provide explicit type promotion and coercion.

Expand Down Expand Up @@ -1093,7 +1099,10 @@ def astype_nansafe(
raise ValueError("dtype must be np.dtype or ExtensionDtype")

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

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

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

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

if is_string_dtype(inferred_dtype):
if not convert_string:
inferred_dtype = input_array.dtype
return input_array.dtype
else:
inferred_dtype = pandas_dtype("string")
return inferred_dtype
return pandas_dtype("string")

if convert_integer:
target_int_dtype = pandas_dtype("Int64")
Expand Down Expand Up @@ -1454,7 +1466,9 @@ def convert_dtypes(
else:
return input_array.dtype

return inferred_dtype
# error: Incompatible return value type (got "Union[str, Union[dtype[Any],
# ExtensionDtype]]", expected "Union[dtype[Any], ExtensionDtype]")
return inferred_dtype # type: ignore[return-value]


def maybe_infer_to_datetimelike(
Expand Down Expand Up @@ -1831,7 +1845,9 @@ def construct_2d_arraylike_from_scalar(

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

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

elif dtype.kind == "S":
Expand Down
6 changes: 2 additions & 4 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -647,7 +647,7 @@ def __init__(
elif isinstance(data, (np.ndarray, Series, Index)):
if data.dtype.names:
# i.e. numpy structured array

data = cast(np.ndarray, data)
mgr = rec_array_to_mgr(
data,
index,
Expand Down Expand Up @@ -2279,9 +2279,7 @@ def to_records(
if dtype_mapping is None:
formats.append(v.dtype)
elif isinstance(dtype_mapping, (type, np.dtype, str)):
# error: Argument 1 to "append" of "list" has incompatible type
# "Union[type, dtype, str]"; expected "dtype"
formats.append(dtype_mapping) # type: ignore[arg-type]
formats.append(dtype_mapping)
else:
element = "row" if i < index_len else "column"
msg = f"Invalid dtype {dtype_mapping} specified for {element} {name}"
Expand Down
8 changes: 3 additions & 5 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -9751,11 +9751,9 @@ def abs(self: FrameOrSeries) -> FrameOrSeries:
2 6 30 -30
3 7 40 -50
"""
# error: Argument 1 to "__call__" of "ufunc" has incompatible type
# "FrameOrSeries"; expected "Union[Union[int, float, complex, str, bytes,
# generic], Sequence[Union[int, float, complex, str, bytes, generic]],
# Sequence[Sequence[Any]], _SupportsArray]"
return np.abs(self) # type: ignore[arg-type]
# error: Incompatible return value type (got "ndarray[Any, dtype[Any]]",
# expected "FrameOrSeries")
return np.abs(self) # type: ignore[return-value]

@final
def describe(
Expand Down
4 changes: 3 additions & 1 deletion pandas/core/groupby/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,9 @@ def _get_cython_function(
f = getattr(libgroupby, ftype)
if is_numeric:
return f
elif dtype == object:
# error: Non-overlapping equality check (left operand type: "dtype[Any]", right
# operand type: "Literal['object']")
elif dtype == object: # type: ignore[comparison-overlap]
if "object" not in f.__signatures__:
# raise NotImplementedError here rather than TypeError later
raise NotImplementedError(
Expand Down
4 changes: 3 additions & 1 deletion pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,9 @@ def _dtype_to_subclass(cls, dtype: DtypeObj):

return Int64Index

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

Expand Down
7 changes: 1 addition & 6 deletions pandas/core/indexes/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,17 +187,12 @@ def _can_hold_strings(self):
def _engine_type(self):
# self.codes can have dtype int8, int16, int32 or int64, so we need
# to return the corresponding engine type (libindex.Int8Engine, etc.).

# error: Invalid index type "Type[generic]" for "Dict[Type[signedinteger[Any]],
# Any]"; expected type "Type[signedinteger[Any]]"
return {
np.int8: libindex.Int8Engine,
np.int16: libindex.Int16Engine,
np.int32: libindex.Int32Engine,
np.int64: libindex.Int64Engine,
}[
self.codes.dtype.type # type: ignore[index]
]
}[self.codes.dtype.type]

_attributes = ["name"]

Expand Down
4 changes: 3 additions & 1 deletion pandas/core/indexes/extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,11 +397,13 @@ def astype(self, dtype, copy: bool = True) -> Index:
return self
return self.copy()

# error: Non-overlapping equality check (left operand type: "dtype[Any]", right
# operand type: "Literal['M8[ns]']")
if (
isinstance(self.dtype, np.dtype)
and isinstance(dtype, np.dtype)
and dtype.kind == "M"
and dtype != "M8[ns]"
and dtype != "M8[ns]" # type: ignore[comparison-overlap]
):
# For now Datetime supports this by unwrapping ndarray, but DTI doesn't
raise TypeError(f"Cannot cast {type(self).__name__} to dtype")
Expand Down
16 changes: 9 additions & 7 deletions pandas/core/internals/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -1167,13 +1167,17 @@ def shift(self, periods: int, axis: int = 0, fill_value: Any = None) -> list[Blo
# convert integer to float if necessary. need to do a lot more than
# that, handle boolean etc also

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

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

return [self.make_block(new_values)]

Expand Down Expand Up @@ -1894,9 +1898,7 @@ def get_block_type(values, dtype: Dtype | None = None):
cls = ExtensionBlock
elif isinstance(dtype, CategoricalDtype):
cls = CategoricalBlock
# error: Non-overlapping identity check (left operand type: "Type[generic]",
# right operand type: "Type[Timestamp]")
elif vtype is Timestamp: # type: ignore[comparison-overlap]
elif vtype is Timestamp:
cls = DatetimeTZBlock
elif isinstance(dtype, ExtensionDtype):
# Note: need to be sure PandasArray is unwrapped before we get here
Expand Down
4 changes: 4 additions & 0 deletions pandas/core/internals/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
Any,
Hashable,
Sequence,
cast,
)
import warnings

Expand Down Expand Up @@ -165,6 +166,9 @@ def rec_array_to_mgr(

# fill if needed
if isinstance(data, np.ma.MaskedArray):
# GH#42200 we only get here with MaskedRecords, but check for the
# parent class MaskedArray to avoid the need to import MaskedRecords
data = cast("MaskedRecords", data)
new_arrays = fill_masked_arrays(data, arr_columns)
else:
# error: Incompatible types in assignment (expression has type
Expand Down
Loading