Skip to content

Commit d91fcfc

Browse files
jbrockmendelJulianWgs
authored andcommitted
TYP: fix type ignores (pandas-dev#40434)
1 parent e390d1e commit d91fcfc

File tree

9 files changed

+60
-84
lines changed

9 files changed

+60
-84
lines changed

pandas/_testing/_io.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -93,9 +93,7 @@ def dec(f):
9393
is_decorating = not kwargs and len(args) == 1 and callable(args[0])
9494
if is_decorating:
9595
f = args[0]
96-
# error: Incompatible types in assignment (expression has type
97-
# "List[<nothing>]", variable has type "Tuple[Any, ...]")
98-
args = [] # type: ignore[assignment]
96+
args = ()
9997
return dec(f)
10098
else:
10199
return dec

pandas/compat/numpy/__init__.py

+15-17
Original file line numberDiff line numberDiff line change
@@ -27,41 +27,39 @@
2727
_tz_regex = re.compile("[+-]0000$")
2828

2929

30-
def tz_replacer(s):
31-
if isinstance(s, str):
32-
if s.endswith("Z"):
33-
s = s[:-1]
34-
elif _tz_regex.search(s):
35-
s = s[:-5]
36-
return s
30+
def _tz_replacer(tstring):
31+
if isinstance(tstring, str):
32+
if tstring.endswith("Z"):
33+
tstring = tstring[:-1]
34+
elif _tz_regex.search(tstring):
35+
tstring = tstring[:-5]
36+
return tstring
3737

3838

39-
def np_datetime64_compat(s, *args, **kwargs):
39+
def np_datetime64_compat(tstring: str, unit: str = "ns"):
4040
"""
4141
provide compat for construction of strings to numpy datetime64's with
4242
tz-changes in 1.11 that make '2015-01-01 09:00:00Z' show a deprecation
4343
warning, when need to pass '2015-01-01 09:00:00'
4444
"""
45-
s = tz_replacer(s)
46-
# error: No overload variant of "datetime64" matches argument types "Any",
47-
# "Tuple[Any, ...]", "Dict[str, Any]"
48-
return np.datetime64(s, *args, **kwargs) # type: ignore[call-overload]
45+
tstring = _tz_replacer(tstring)
46+
return np.datetime64(tstring, unit)
4947

5048

51-
def np_array_datetime64_compat(arr, *args, **kwargs):
49+
def np_array_datetime64_compat(arr, dtype="M8[ns]"):
5250
"""
5351
provide compat for construction of an array of strings to a
5452
np.array(..., dtype=np.datetime64(..))
5553
tz-changes in 1.11 that make '2015-01-01 09:00:00Z' show a deprecation
5654
warning, when need to pass '2015-01-01 09:00:00'
5755
"""
58-
# is_list_like
56+
# is_list_like; can't import as it would be circular
5957
if hasattr(arr, "__iter__") and not isinstance(arr, (str, bytes)):
60-
arr = [tz_replacer(s) for s in arr]
58+
arr = [_tz_replacer(s) for s in arr]
6159
else:
62-
arr = tz_replacer(arr)
60+
arr = _tz_replacer(arr)
6361

64-
return np.array(arr, *args, **kwargs)
62+
return np.array(arr, dtype=dtype)
6563

6664

6765
__all__ = [

pandas/core/dtypes/concat.py

+10-11
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@
1414
from pandas.core.dtypes.common import (
1515
is_categorical_dtype,
1616
is_dtype_equal,
17-
is_extension_array_dtype,
1817
is_sparse,
1918
)
19+
from pandas.core.dtypes.dtypes import ExtensionDtype
2020
from pandas.core.dtypes.generic import (
2121
ABCCategoricalIndex,
2222
ABCSeries,
@@ -64,14 +64,13 @@ def _cast_to_common_type(arr: ArrayLike, dtype: DtypeObj) -> ArrayLike:
6464
# are not coming from Index/Series._values), eg in BlockManager.quantile
6565
arr = ensure_wrapped_if_datetimelike(arr)
6666

67-
if is_extension_array_dtype(dtype) and isinstance(arr, np.ndarray):
68-
# numpy's astype cannot handle ExtensionDtypes
69-
return pd_array(arr, dtype=dtype, copy=False)
70-
# error: Argument 1 to "astype" of "_ArrayOrScalarCommon" has incompatible type
71-
# "Union[dtype[Any], ExtensionDtype]"; expected "Union[dtype[Any], None, type,
72-
# _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, Union[int, Sequence[int]]],
73-
# List[Any], _DTypeDict, Tuple[Any, Any]]]"
74-
return arr.astype(dtype, copy=False) # type: ignore[arg-type]
67+
if isinstance(dtype, ExtensionDtype):
68+
if isinstance(arr, np.ndarray):
69+
# numpy's astype cannot handle ExtensionDtypes
70+
return pd_array(arr, dtype=dtype, copy=False)
71+
return arr.astype(dtype, copy=False)
72+
73+
return arr.astype(dtype, copy=False)
7574

7675

7776
def concat_compat(to_concat, axis: int = 0, ea_compat_axis: bool = False):
@@ -115,7 +114,7 @@ def is_nonempty(x) -> bool:
115114

116115
all_empty = not len(non_empties)
117116
single_dtype = len({x.dtype for x in to_concat}) == 1
118-
any_ea = any(is_extension_array_dtype(x.dtype) for x in to_concat)
117+
any_ea = any(isinstance(x.dtype, ExtensionDtype) for x in to_concat)
119118

120119
if any_ea:
121120
# we ignore axis here, as internally concatting with EAs is always
@@ -354,7 +353,7 @@ def _concat_datetime(to_concat, axis=0):
354353

355354
result = type(to_concat[0])._concat_same_type(to_concat, axis=axis)
356355

357-
if result.ndim == 2 and is_extension_array_dtype(result.dtype):
356+
if result.ndim == 2 and isinstance(result.dtype, ExtensionDtype):
358357
# TODO(EA2D): kludge not necessary with 2D EAs
359358
assert result.shape[0] == 1
360359
result = result[0]

pandas/core/dtypes/dtypes.py

+5-13
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ class PandasExtensionDtype(ExtensionDtype):
8383
num = 100
8484
shape: Tuple[int, ...] = ()
8585
itemsize = 8
86-
base = None
86+
base: Optional[DtypeObj] = None
8787
isbuiltin = 0
8888
isnative = 0
8989
_cache: Dict[str_type, PandasExtensionDtype] = {}
@@ -180,9 +180,7 @@ class CategoricalDtype(PandasExtensionDtype, ExtensionDtype):
180180
type: Type[CategoricalDtypeType] = CategoricalDtypeType
181181
kind: str_type = "O"
182182
str = "|O08"
183-
# error: Incompatible types in assignment (expression has type "dtype",
184-
# base class "PandasExtensionDtype" defined the type as "None")
185-
base = np.dtype("O") # type: ignore[assignment]
183+
base = np.dtype("O")
186184
_metadata = ("categories", "ordered")
187185
_cache: Dict[str_type, PandasExtensionDtype] = {}
188186

@@ -676,9 +674,7 @@ class DatetimeTZDtype(PandasExtensionDtype):
676674
kind: str_type = "M"
677675
str = "|M8[ns]"
678676
num = 101
679-
# error: Incompatible types in assignment (expression has type "dtype",
680-
# base class "PandasExtensionDtype" defined the type as "None")
681-
base = np.dtype("M8[ns]") # type: ignore[assignment]
677+
base = np.dtype("M8[ns]")
682678
na_value = NaT
683679
_metadata = ("unit", "tz")
684680
_match = re.compile(r"(datetime64|M8)\[(?P<unit>.+), (?P<tz>.+)\]")
@@ -844,9 +840,7 @@ class PeriodDtype(dtypes.PeriodDtypeBase, PandasExtensionDtype):
844840
type: Type[Period] = Period
845841
kind: str_type = "O"
846842
str = "|O08"
847-
# error: Incompatible types in assignment (expression has type "dtype",
848-
# base class "PandasExtensionDtype" defined the type as "None")
849-
base = np.dtype("O") # type: ignore[assignment]
843+
base = np.dtype("O")
850844
num = 102
851845
_metadata = ("freq",)
852846
_match = re.compile(r"(P|p)eriod\[(?P<freq>.+)\]")
@@ -1046,9 +1040,7 @@ class IntervalDtype(PandasExtensionDtype):
10461040
name = "interval"
10471041
kind: str_type = "O"
10481042
str = "|O08"
1049-
# error: Incompatible types in assignment (expression has type "dtype",
1050-
# base class "PandasExtensionDtype" defined the type as "None")
1051-
base = np.dtype("O") # type: ignore[assignment]
1043+
base = np.dtype("O")
10521044
num = 103
10531045
_metadata = (
10541046
"subtype",

pandas/core/indexes/numeric.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -292,12 +292,9 @@ def _convert_arr_indexer(self, keyarr):
292292
if is_integer_dtype(keyarr) or (
293293
lib.infer_dtype(keyarr, skipna=False) == "integer"
294294
):
295-
dtype = np.uint64
295+
dtype = np.dtype(np.uint64)
296296

297-
# error: Argument "dtype" to "asarray_tuplesafe" has incompatible type
298-
# "Optional[Type[unsignedinteger[Any]]]"; expected "Union[str, dtype[Any],
299-
# None]"
300-
return com.asarray_tuplesafe(keyarr, dtype=dtype) # type: ignore[arg-type]
297+
return com.asarray_tuplesafe(keyarr, dtype=dtype)
301298

302299

303300
_float64_descr_args = {

pandas/core/indexes/range.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from typing import (
77
TYPE_CHECKING,
88
Any,
9+
Callable,
910
Hashable,
1011
List,
1112
Optional,
@@ -900,7 +901,7 @@ def _arith_method(self, other, op):
900901
]:
901902
return op(self._int64index, other)
902903

903-
step = False
904+
step: Optional[Callable] = None
904905
if op in [operator.mul, ops.rmul, operator.truediv, ops.rtruediv]:
905906
step = op
906907

@@ -913,8 +914,7 @@ def _arith_method(self, other, op):
913914
# apply if we have an override
914915
if step:
915916
with np.errstate(all="ignore"):
916-
# error: "bool" not callable
917-
rstep = step(left.step, right) # type: ignore[operator]
917+
rstep = step(left.step, right)
918918

919919
# we don't have a representable op
920920
# so return a base index

pandas/core/internals/api.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,10 @@
1313
from pandas._libs.internals import BlockPlacement
1414
from pandas._typing import Dtype
1515

16-
from pandas.core.dtypes.common import is_datetime64tz_dtype
16+
from pandas.core.dtypes.common import (
17+
is_datetime64tz_dtype,
18+
pandas_dtype,
19+
)
1720

1821
from pandas.core.arrays import DatetimeArray
1922
from pandas.core.internals.blocks import (
@@ -40,11 +43,10 @@ def make_block(
4043
- Block.make_block_same_class
4144
- Block.__init__
4245
"""
43-
# error: Argument 2 to "extract_pandas_array" has incompatible type
44-
# "Union[ExtensionDtype, str, dtype[Any], Type[str], Type[float], Type[int],
45-
# Type[complex], Type[bool], Type[object], None]"; expected "Union[dtype[Any],
46-
# ExtensionDtype, None]"
47-
values, dtype = extract_pandas_array(values, dtype, ndim) # type: ignore[arg-type]
46+
if dtype is not None:
47+
dtype = pandas_dtype(dtype)
48+
49+
values, dtype = extract_pandas_array(values, dtype, ndim)
4850

4951
if klass is None:
5052
dtype = dtype or values.dtype

pandas/core/nanops.py

+9-18
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
DtypeObj,
2929
F,
3030
Scalar,
31+
Shape,
3132
)
3233
from pandas.compat._optional import import_optional_dependency
3334

@@ -650,22 +651,16 @@ def nanmean(
650651
values, skipna, fill_value=0, mask=mask
651652
)
652653
dtype_sum = dtype_max
653-
dtype_count = np.float64
654+
dtype_count = np.dtype(np.float64)
654655

655656
# not using needs_i8_conversion because that includes period
656657
if dtype.kind in ["m", "M"]:
657-
# error: Incompatible types in assignment (expression has type "Type[float64]",
658-
# variable has type "dtype[Any]")
659-
dtype_sum = np.float64 # type: ignore[assignment]
658+
dtype_sum = np.dtype(np.float64)
660659
elif is_integer_dtype(dtype):
661-
# error: Incompatible types in assignment (expression has type "Type[float64]",
662-
# variable has type "dtype[Any]")
663-
dtype_sum = np.float64 # type: ignore[assignment]
660+
dtype_sum = np.dtype(np.float64)
664661
elif is_float_dtype(dtype):
665662
dtype_sum = dtype
666-
# error: Incompatible types in assignment (expression has type "dtype[Any]",
667-
# variable has type "Type[float64]")
668-
dtype_count = dtype # type: ignore[assignment]
663+
dtype_count = dtype
669664

670665
count = _get_counts(values.shape, mask, axis, dtype=dtype_count)
671666
the_sum = _ensure_numeric(values.sum(axis, dtype=dtype_sum))
@@ -787,7 +782,7 @@ def get_empty_reduction_result(
787782

788783

789784
def _get_counts_nanvar(
790-
value_counts: Tuple[int],
785+
values_shape: Shape,
791786
mask: Optional[np.ndarray],
792787
axis: Optional[int],
793788
ddof: int,
@@ -799,7 +794,7 @@ def _get_counts_nanvar(
799794
800795
Parameters
801796
----------
802-
values_shape : Tuple[int]
797+
values_shape : Tuple[int, ...]
803798
shape tuple from values ndarray, used if mask is None
804799
mask : Optional[ndarray[bool]]
805800
locations in values that should be considered missing
@@ -816,7 +811,7 @@ def _get_counts_nanvar(
816811
d : scalar or array
817812
"""
818813
dtype = get_dtype(dtype)
819-
count = _get_counts(value_counts, mask, axis, dtype=dtype)
814+
count = _get_counts(values_shape, mask, axis, dtype=dtype)
820815
# error: Unsupported operand types for - ("int" and "generic")
821816
# error: Unsupported operand types for - ("float" and "generic")
822817
d = count - dtype.type(ddof) # type: ignore[operator]
@@ -991,11 +986,7 @@ def nansem(
991986
if not is_float_dtype(values.dtype):
992987
values = values.astype("f8")
993988

994-
# error: Argument 1 to "_get_counts_nanvar" has incompatible type
995-
# "Tuple[int, ...]"; expected "Tuple[int]"
996-
count, _ = _get_counts_nanvar(
997-
values.shape, mask, axis, ddof, values.dtype # type: ignore[arg-type]
998-
)
989+
count, _ = _get_counts_nanvar(values.shape, mask, axis, ddof, values.dtype)
999990
var = nanvar(values, axis=axis, skipna=skipna, ddof=ddof)
1000991

1001992
return np.sqrt(var) / np.sqrt(count)

pandas/io/formats/format.py

+7-8
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,11 @@
8282
notna,
8383
)
8484

85-
from pandas.core.arrays.datetimes import DatetimeArray
86-
from pandas.core.arrays.timedeltas import TimedeltaArray
85+
from pandas.core.arrays import (
86+
Categorical,
87+
DatetimeArray,
88+
TimedeltaArray,
89+
)
8790
from pandas.core.base import PandasObject
8891
import pandas.core.common as com
8992
from pandas.core.construction import extract_array
@@ -106,7 +109,6 @@
106109

107110
if TYPE_CHECKING:
108111
from pandas import (
109-
Categorical,
110112
DataFrame,
111113
Series,
112114
)
@@ -1565,12 +1567,9 @@ def _format_strings(self) -> List[str]:
15651567
# no attribute "_formatter"
15661568
formatter = values._formatter(boxed=True) # type: ignore[union-attr]
15671569

1568-
if is_categorical_dtype(values.dtype):
1570+
if isinstance(values, Categorical):
15691571
# Categorical is special for now, so that we can preserve tzinfo
1570-
1571-
# error: Item "ExtensionArray" of "Union[Any, ExtensionArray]" has no
1572-
# attribute "_internal_get_values"
1573-
array = values._internal_get_values() # type: ignore[union-attr]
1572+
array = values._internal_get_values()
15741573
else:
15751574
array = np.asarray(values)
15761575

0 commit comments

Comments
 (0)