Skip to content

Commit 8c9621d

Browse files
authored
TYP: fix type:ignores (pandas-dev#40758)
1 parent 9e4f54f commit 8c9621d

File tree

12 files changed

+44
-67
lines changed

12 files changed

+44
-67
lines changed

pandas/core/arrays/datetimelike.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1732,8 +1732,8 @@ def _round(self, freq, mode, ambiguous, nonexistent):
17321732
values = self.view("i8")
17331733
values = cast(np.ndarray, values)
17341734
nanos = to_offset(freq).nanos
1735-
result = round_nsint64(values, mode, nanos)
1736-
result = self._maybe_mask_results(result, fill_value=iNaT)
1735+
result_i8 = round_nsint64(values, mode, nanos)
1736+
result = self._maybe_mask_results(result_i8, fill_value=iNaT)
17371737
result = result.view(self._ndarray.dtype)
17381738
return self._simple_new(result, dtype=self.dtype)
17391739

pandas/core/arrays/integer.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -371,14 +371,14 @@ def astype(self, dtype, copy: bool = True) -> ArrayLike:
371371
if isinstance(dtype, ExtensionDtype):
372372
return super().astype(dtype, copy=copy)
373373

374+
na_value: float | np.datetime64 | lib.NoDefault
375+
374376
# coerce
375377
if is_float_dtype(dtype):
376378
# In astype, we consider dtype=float to also mean na_value=np.nan
377379
na_value = np.nan
378380
elif is_datetime64_dtype(dtype):
379-
# error: Incompatible types in assignment (expression has type
380-
# "datetime64", variable has type "float")
381-
na_value = np.datetime64("NaT") # type: ignore[assignment]
381+
na_value = np.datetime64("NaT")
382382
else:
383383
na_value = lib.no_default
384384

pandas/core/construction.py

+8-14
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,10 @@
5252
is_integer_dtype,
5353
is_list_like,
5454
is_object_dtype,
55-
is_sparse,
5655
is_string_dtype,
5756
is_timedelta64_ns_dtype,
5857
)
58+
from pandas.core.dtypes.dtypes import DatetimeTZDtype
5959
from pandas.core.dtypes.generic import (
6060
ABCExtensionArray,
6161
ABCIndex,
@@ -549,12 +549,10 @@ def sanitize_array(
549549

550550
subarr = _sanitize_ndim(subarr, data, dtype, index)
551551

552-
if not (is_extension_array_dtype(subarr.dtype) or is_extension_array_dtype(dtype)):
553-
# error: Argument 1 to "_sanitize_str_dtypes" has incompatible type
554-
# "ExtensionArray"; expected "ndarray"
555-
subarr = _sanitize_str_dtypes(
556-
subarr, data, dtype, copy # type: ignore[arg-type]
557-
)
552+
if not (
553+
isinstance(subarr.dtype, ExtensionDtype) or isinstance(dtype, ExtensionDtype)
554+
):
555+
subarr = _sanitize_str_dtypes(subarr, data, dtype, copy)
558556

559557
is_object_or_str_dtype = is_object_dtype(dtype) or is_string_dtype(dtype)
560558
if is_object_dtype(subarr.dtype) and not is_object_or_str_dtype:
@@ -599,7 +597,7 @@ def _sanitize_ndim(
599597

600598

601599
def _sanitize_str_dtypes(
602-
result: np.ndarray, data, dtype: Optional[DtypeObj], copy: bool
600+
result: np.ndarray, data, dtype: Optional[np.dtype], copy: bool
603601
) -> np.ndarray:
604602
"""
605603
Ensure we have a dtype that is supported by pandas.
@@ -613,11 +611,7 @@ def _sanitize_str_dtypes(
613611
# GH#19853: If data is a scalar, result has already the result
614612
if not lib.is_scalar(data):
615613
if not np.all(isna(data)):
616-
# error: Argument "dtype" to "array" has incompatible type
617-
# "Union[dtype[Any], ExtensionDtype, None]"; expected "Union[dtype[Any],
618-
# None, type, _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any,
619-
# Union[int, Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]"
620-
data = np.array(data, dtype=dtype, copy=False) # type: ignore[arg-type]
614+
data = np.array(data, dtype=dtype, copy=False)
621615
result = np.array(data, dtype=object, copy=copy)
622616
return result
623617

@@ -666,7 +660,7 @@ def _try_cast(
666660
):
667661
return arr
668662

669-
if isinstance(dtype, ExtensionDtype) and (dtype.kind != "M" or is_sparse(dtype)):
663+
if isinstance(dtype, ExtensionDtype) and not isinstance(dtype, DatetimeTZDtype):
670664
# create an extension array from its dtype
671665
# DatetimeTZ case needs to go through maybe_cast_to_datetime but
672666
# SparseDtype does not

pandas/core/dtypes/cast.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1400,11 +1400,13 @@ def soft_convert_objects(
14001400
# GH 20380, when datetime is beyond year 2262, hence outside
14011401
# bound of nanosecond-resolution 64-bit integers.
14021402
try:
1403-
values = lib.maybe_convert_objects(
1403+
converted = lib.maybe_convert_objects(
14041404
values, convert_datetime=datetime, convert_timedelta=timedelta
14051405
)
14061406
except (OutOfBoundsDatetime, ValueError):
14071407
return values
1408+
if converted is not values:
1409+
return converted
14081410

14091411
if numeric and is_object_dtype(values.dtype):
14101412
converted = lib.maybe_convert_numeric(values, set(), coerce_numeric=True)
@@ -1446,10 +1448,9 @@ def convert_dtypes(
14461448
dtype
14471449
new dtype
14481450
"""
1449-
is_extension = is_extension_array_dtype(input_array.dtype)
14501451
if (
14511452
convert_string or convert_integer or convert_boolean or convert_floating
1452-
) and not is_extension:
1453+
) and isinstance(input_array, np.ndarray):
14531454
inferred_dtype = lib.infer_dtype(input_array)
14541455

14551456
if not convert_string and is_string_dtype(inferred_dtype):

pandas/core/frame.py

+11-17
Original file line numberDiff line numberDiff line change
@@ -3300,14 +3300,10 @@ def transpose(self, *args, copy: bool = False) -> DataFrame:
33003300
)
33013301

33023302
else:
3303-
# error: Incompatible types in assignment (expression has type
3304-
# "ndarray", variable has type "List[Any]")
3305-
new_values = self.values.T # type: ignore[assignment]
3303+
new_arr = self.values.T
33063304
if copy:
3307-
new_values = new_values.copy()
3308-
result = self._constructor(
3309-
new_values, index=self.columns, columns=self.index
3310-
)
3305+
new_arr = new_arr.copy()
3306+
result = self._constructor(new_arr, index=self.columns, columns=self.index)
33113307

33123308
return result.__finalize__(self, method="transpose")
33133309

@@ -3682,17 +3678,15 @@ def _set_item_frame_value(self, key, value: DataFrame) -> None:
36823678
value = value.reindex(cols, axis=1)
36833679

36843680
# now align rows
3681+
arraylike = _reindex_for_setitem(value, self.index)
3682+
self._set_item_mgr(key, arraylike)
36853683

3686-
# error: Incompatible types in assignment (expression has type "ExtensionArray",
3687-
# variable has type "DataFrame")
3688-
value = _reindex_for_setitem(value, self.index) # type: ignore[assignment]
3689-
self._set_item_mgr(key, value)
3690-
3691-
def _iset_item_mgr(self, loc: int, value) -> None:
3684+
def _iset_item_mgr(self, loc: int | slice | np.ndarray, value) -> None:
3685+
# when called from _set_item_mgr loc can be anything returned from get_loc
36923686
self._mgr.iset(loc, value)
36933687
self._clear_item_cache()
36943688

3695-
def _set_item_mgr(self, key, value):
3689+
def _set_item_mgr(self, key, value: ArrayLike) -> None:
36963690
try:
36973691
loc = self._info_axis.get_loc(key)
36983692
except KeyError:
@@ -3707,9 +3701,9 @@ def _set_item_mgr(self, key, value):
37073701
if len(self):
37083702
self._check_setitem_copy()
37093703

3710-
def _iset_item(self, loc: int, value):
3711-
value = self._sanitize_column(value)
3712-
self._iset_item_mgr(loc, value)
3704+
def _iset_item(self, loc: int, value) -> None:
3705+
arraylike = self._sanitize_column(value)
3706+
self._iset_item_mgr(loc, arraylike)
37133707

37143708
# check if we are modifying a copy
37153709
# try to set first as we want an invalid

pandas/core/generic.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -3541,7 +3541,8 @@ def _maybe_cache_changed(self, item, value) -> None:
35413541
The object has called back to us saying maybe it has changed.
35423542
"""
35433543
loc = self._info_axis.get_loc(item)
3544-
self._mgr.iset(loc, value)
3544+
arraylike = value._values
3545+
self._mgr.iset(loc, arraylike)
35453546

35463547
@final
35473548
@property

pandas/core/internals/array_manager.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -850,7 +850,7 @@ def idelete(self, indexer):
850850
self._axes = [self._axes[0], self._axes[1][to_keep]]
851851
return self
852852

853-
def iset(self, loc: Union[int, slice, np.ndarray], value):
853+
def iset(self, loc: Union[int, slice, np.ndarray], value: ArrayLike):
854854
"""
855855
Set new column(s).
856856
@@ -861,12 +861,10 @@ def iset(self, loc: Union[int, slice, np.ndarray], value):
861861
----------
862862
loc : integer, slice or boolean mask
863863
Positional location (already bounds checked)
864-
value : array-like
864+
value : np.ndarray or ExtensionArray
865865
"""
866866
# single column -> single integer index
867867
if lib.is_integer(loc):
868-
# TODO the extract array should in theory not be needed?
869-
value = extract_array(value, extract_numpy=True)
870868

871869
# TODO can we avoid needing to unpack this here? That means converting
872870
# DataFrame into 1D array when loc is an integer
@@ -904,7 +902,10 @@ def iset(self, loc: Union[int, slice, np.ndarray], value):
904902
assert value.shape[0] == len(self._axes[0])
905903

906904
for value_idx, mgr_idx in enumerate(indices):
907-
value_arr = value[:, value_idx]
905+
# error: Invalid index type "Tuple[slice, int]" for
906+
# "Union[ExtensionArray, ndarray]"; expected type
907+
# "Union[int, slice, ndarray]"
908+
value_arr = value[:, value_idx] # type: ignore[index]
908909
self.arrays[mgr_idx] = value_arr
909910
return
910911

pandas/core/internals/construction.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -843,8 +843,8 @@ def _list_of_dict_to_arrays(
843843
if columns is None:
844844
gen = (list(x.keys()) for x in data)
845845
sort = not any(isinstance(d, dict) for d in data)
846-
columns = lib.fast_unique_multiple_list_gen(gen, sort=sort)
847-
columns = ensure_index(columns)
846+
pre_cols = lib.fast_unique_multiple_list_gen(gen, sort=sort)
847+
columns = ensure_index(pre_cols)
848848

849849
# assure that they are of the base dict class and not of derived
850850
# classes

pandas/core/internals/managers.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1062,7 +1062,7 @@ def idelete(self, indexer) -> BlockManager:
10621062
axes = [new_columns, self.axes[1]]
10631063
return type(self)._simple_new(tuple(nbs), axes)
10641064

1065-
def iset(self, loc: Union[int, slice, np.ndarray], value):
1065+
def iset(self, loc: Union[int, slice, np.ndarray], value: ArrayLike):
10661066
"""
10671067
Set new item in-place. Does not consolidate. Adds new Block if not
10681068
contained in the current set of items
@@ -1073,6 +1073,7 @@ def iset(self, loc: Union[int, slice, np.ndarray], value):
10731073
if self._blklocs is None and self.ndim > 1:
10741074
self._rebuild_blknos_and_blklocs()
10751075

1076+
# Note: we exclude DTA/TDA here
10761077
value_is_extension_type = is_extension_array_dtype(value)
10771078

10781079
# categorical/sparse/datetimetz
@@ -1429,7 +1430,7 @@ def _slice_take_blocks_ax0(
14291430

14301431
return blocks
14311432

1432-
def _make_na_block(self, placement, fill_value=None):
1433+
def _make_na_block(self, placement: BlockPlacement, fill_value=None) -> Block:
14331434

14341435
if fill_value is None:
14351436
fill_value = np.nan

pandas/core/missing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -888,7 +888,7 @@ def clean_reindex_fill_method(method):
888888
return clean_fill_method(method, allow_nearest=True)
889889

890890

891-
def _interp_limit(invalid, fw_limit, bw_limit):
891+
def _interp_limit(invalid: np.ndarray, fw_limit, bw_limit):
892892
"""
893893
Get indexers of values that won't be filled
894894
because they exceed the limits.

pandas/core/strings/object_array.py

+2-6
Original file line numberDiff line numberDiff line change
@@ -56,21 +56,17 @@ def _str_map(self, f, na_value=None, dtype: Optional[Dtype] = None):
5656
dtype : Dtype, optional
5757
The dtype of the result array.
5858
"""
59-
arr = self
6059
if dtype is None:
6160
dtype = np.dtype("object")
6261
if na_value is None:
6362
na_value = self._str_na_value
6463

65-
if not len(arr):
64+
if not len(self):
6665
# error: Argument 1 to "ndarray" has incompatible type "int";
6766
# expected "Sequence[int]"
6867
return np.ndarray(0, dtype=dtype) # type: ignore[arg-type]
6968

70-
if not isinstance(arr, np.ndarray):
71-
# error: Incompatible types in assignment (expression has type "ndarray",
72-
# variable has type "ObjectStringArrayMixin")
73-
arr = np.asarray(arr, dtype=object) # type: ignore[assignment]
69+
arr = np.asarray(self, dtype=object)
7470
mask = isna(arr)
7571
convert = not np.all(mask)
7672
try:

pandas/tests/extension/test_numpy.py

-11
Original file line numberDiff line numberDiff line change
@@ -330,17 +330,6 @@ def test_fillna_frame(self, data_missing):
330330
# Non-scalar "scalar" values.
331331
super().test_fillna_frame(data_missing)
332332

333-
def test_fillna_fill_other(self, data_missing):
334-
# Same as the parent class test, but with PandasDtype for expected["B"]
335-
# instead of equivalent numpy dtype
336-
data = data_missing
337-
result = pd.DataFrame({"A": data, "B": [np.nan] * len(data)}).fillna({"B": 0.0})
338-
339-
expected = pd.DataFrame({"A": data, "B": [0.0] * len(result)})
340-
expected["B"] = expected["B"].astype(PandasDtype(expected["B"].dtype))
341-
342-
self.assert_frame_equal(result, expected)
343-
344333

345334
class TestReshaping(BaseNumPyTests, base.BaseReshapingTests):
346335
@pytest.mark.skip(reason="Incorrect expected.")

0 commit comments

Comments
 (0)