Skip to content

Commit 385a2ca

Browse files
TYP: Add MyPy Error Codes (#35311)
1 parent 69cd744 commit 385a2ca

37 files changed

+170
-77
lines changed

ci/code_checks.sh

+5
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,11 @@ if [[ -z "$CHECK" || "$CHECK" == "patterns" ]]; then
230230
invgrep -R --include="*.py" -P '# type: (?!ignore)' pandas
231231
RET=$(($RET + $?)) ; echo $MSG "DONE"
232232

233+
# https://github.com/python/mypy/issues/7384
234+
# MSG='Check for missing error codes with # type: ignore' ; echo $MSG
235+
# invgrep -R --include="*.py" -P '# type: ignore(?!\[)' pandas
236+
# RET=$(($RET + $?)) ; echo $MSG "DONE"
237+
233238
MSG='Check for use of foo.__class__ instead of type(foo)' ; echo $MSG
234239
invgrep -R --include=*.{py,pyx} '\.__class__' pandas
235240
RET=$(($RET + $?)) ; echo $MSG "DONE"

environment.yml

+1
Original file line numberDiff line numberDiff line change
@@ -109,3 +109,4 @@ dependencies:
109109
- pip:
110110
- git+https://github.com/pandas-dev/pydata-sphinx-theme.git@master
111111
- git+https://github.com/numpy/numpydoc
112+
- pyflakes>=2.2.0

pandas/_config/config.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -462,7 +462,7 @@ def register_option(
462462
for k in path:
463463
# NOTE: tokenize.Name is not a public constant
464464
# error: Module has no attribute "Name" [attr-defined]
465-
if not re.match("^" + tokenize.Name + "$", k): # type: ignore
465+
if not re.match("^" + tokenize.Name + "$", k): # type: ignore[attr-defined]
466466
raise ValueError(f"{k} is not a valid identifier")
467467
if keyword.iskeyword(k):
468468
raise ValueError(f"{k} is a python keyword")

pandas/compat/pickle_compat.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ class _LoadSparseSeries:
6464
# https://github.com/python/mypy/issues/1020
6565
# error: Incompatible return type for "__new__" (returns "Series", but must return
6666
# a subtype of "_LoadSparseSeries")
67-
def __new__(cls) -> "Series": # type: ignore
67+
def __new__(cls) -> "Series": # type: ignore[misc]
6868
from pandas import Series
6969

7070
warnings.warn(
@@ -82,7 +82,7 @@ class _LoadSparseFrame:
8282
# https://github.com/python/mypy/issues/1020
8383
# error: Incompatible return type for "__new__" (returns "DataFrame", but must
8484
# return a subtype of "_LoadSparseFrame")
85-
def __new__(cls) -> "DataFrame": # type: ignore
85+
def __new__(cls) -> "DataFrame": # type: ignore[misc]
8686
from pandas import DataFrame
8787

8888
warnings.warn(
@@ -181,7 +181,7 @@ def __new__(cls) -> "DataFrame": # type: ignore
181181
# functions for compat and uses a non-public class of the pickle module.
182182

183183
# error: Name 'pkl._Unpickler' is not defined
184-
class Unpickler(pkl._Unpickler): # type: ignore
184+
class Unpickler(pkl._Unpickler): # type: ignore[name-defined]
185185
def find_class(self, module, name):
186186
# override superclass
187187
key = (module, name)

pandas/core/algorithms.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -427,7 +427,8 @@ def isin(comps: AnyArrayLike, values: AnyArrayLike) -> np.ndarray:
427427
if is_categorical_dtype(comps):
428428
# TODO(extension)
429429
# handle categoricals
430-
return comps.isin(values) # type: ignore
430+
# error: "ExtensionArray" has no attribute "isin" [attr-defined]
431+
return comps.isin(values) # type: ignore[attr-defined]
431432

432433
comps, dtype = _ensure_data(comps)
433434
values, _ = _ensure_data(values, dtype=dtype)

pandas/core/arrays/datetimelike.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,9 @@ def _ndarray(self) -> np.ndarray:
468468

469469
def _from_backing_data(self: _T, arr: np.ndarray) -> _T:
470470
# Note: we do not retain `freq`
471+
# error: Unexpected keyword argument "dtype" for "NDArrayBackedExtensionArray"
472+
# TODO: add my error code
473+
# https://github.com/python/mypy/issues/7384
471474
return type(self)(arr, dtype=self.dtype) # type: ignore
472475

473476
# ------------------------------------------------------------------
@@ -809,7 +812,8 @@ def _validate_scalar(
809812
value = NaT
810813

811814
elif isinstance(value, self._recognized_scalars):
812-
value = self._scalar_type(value) # type: ignore
815+
# error: Too many arguments for "object" [call-arg]
816+
value = self._scalar_type(value) # type: ignore[call-arg]
813817

814818
else:
815819
if msg is None:
@@ -1129,7 +1133,8 @@ def resolution(self) -> str:
11291133
"""
11301134
Returns day, hour, minute, second, millisecond or microsecond
11311135
"""
1132-
return self._resolution_obj.attrname # type: ignore
1136+
# error: Item "None" of "Optional[Any]" has no attribute "attrname"
1137+
return self._resolution_obj.attrname # type: ignore[union-attr]
11331138

11341139
@classmethod
11351140
def _validate_frequency(cls, index, freq, **kwargs):

pandas/core/arrays/interval.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1057,7 +1057,7 @@ def mid(self):
10571057

10581058
# https://github.com/python/mypy/issues/1362
10591059
# Mypy does not support decorated properties
1060-
@property # type: ignore
1060+
@property # type: ignore[misc]
10611061
@Appender(
10621062
_interval_shared_docs["is_non_overlapping_monotonic"] % _shared_docs_kwargs
10631063
)

pandas/core/arrays/period.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -278,8 +278,8 @@ def _check_compatible_with(self, other, setitem: bool = False):
278278
def dtype(self) -> PeriodDtype:
279279
return self._dtype
280280

281-
# error: Read-only property cannot override read-write property [misc]
282-
@property # type: ignore
281+
# error: Read-only property cannot override read-write property
282+
@property # type: ignore[misc]
283283
def freq(self) -> BaseOffset:
284284
"""
285285
Return the frequency object for this PeriodArray.

pandas/core/computation/expressions.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,8 @@ def evaluate(op, a, b, use_numexpr: bool = True):
227227
if op_str is not None:
228228
use_numexpr = use_numexpr and _bool_arith_check(op_str, a, b)
229229
if use_numexpr:
230-
return _evaluate(op, op_str, a, b) # type: ignore
230+
# error: "None" not callable
231+
return _evaluate(op, op_str, a, b) # type: ignore[misc]
231232
return _evaluate_standard(op, op_str, a, b)
232233

233234

pandas/core/computation/parsing.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,9 @@ def create_valid_python_identifier(name: str) -> str:
3737
special_characters_replacements = {
3838
char: f"_{token.tok_name[tokval]}_"
3939
# The ignore here is because of a bug in mypy that is resolved in 0.740
40-
for char, tokval in tokenize.EXACT_TOKEN_TYPES.items() # type: ignore
40+
for char, tokval in (
41+
tokenize.EXACT_TOKEN_TYPES.items() # type: ignore[attr-defined]
42+
)
4143
}
4244
special_characters_replacements.update(
4345
{

pandas/core/computation/pytables.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def _resolve_name(self):
6363
return self.name
6464

6565
# read-only property overwriting read/write property
66-
@property # type: ignore
66+
@property # type: ignore[misc]
6767
def value(self):
6868
return self._value
6969

pandas/core/config_init.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,7 @@ def is_terminal() -> bool:
327327
"""
328328
try:
329329
# error: Name 'get_ipython' is not defined
330-
ip = get_ipython() # type: ignore
330+
ip = get_ipython() # type: ignore[name-defined]
331331
except NameError: # assume standard Python interpreter in a terminal
332332
return True
333333
else:

pandas/core/dtypes/common.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -136,11 +136,13 @@ def ensure_int_or_float(arr: ArrayLike, copy: bool = False) -> np.array:
136136
"""
137137
# TODO: GH27506 potential bug with ExtensionArrays
138138
try:
139-
return arr.astype("int64", copy=copy, casting="safe") # type: ignore
139+
# error: Unexpected keyword argument "casting" for "astype"
140+
return arr.astype("int64", copy=copy, casting="safe") # type: ignore[call-arg]
140141
except TypeError:
141142
pass
142143
try:
143-
return arr.astype("uint64", copy=copy, casting="safe") # type: ignore
144+
# error: Unexpected keyword argument "casting" for "astype"
145+
return arr.astype("uint64", copy=copy, casting="safe") # type: ignore[call-arg]
144146
except TypeError:
145147
if is_extension_array_dtype(arr.dtype):
146148
return arr.to_numpy(dtype="float64", na_value=np.nan)

pandas/core/dtypes/dtypes.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -635,7 +635,8 @@ class DatetimeTZDtype(PandasExtensionDtype):
635635

636636
def __init__(self, unit: Union[str_type, "DatetimeTZDtype"] = "ns", tz=None):
637637
if isinstance(unit, DatetimeTZDtype):
638-
unit, tz = unit.unit, unit.tz # type: ignore
638+
# error: "str" has no attribute "tz"
639+
unit, tz = unit.unit, unit.tz # type: ignore[attr-defined]
639640

640641
if unit != "ns":
641642
if isinstance(unit, str) and tz is None:

pandas/core/dtypes/generic.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ def create_pandas_abc_type(name, attr, comp):
77

88
# https://github.com/python/mypy/issues/1006
99
# error: 'classmethod' used with a non-method
10-
@classmethod # type: ignore
10+
@classmethod # type: ignore[misc]
1111
def _check(cls, inst) -> bool:
1212
return getattr(inst, attr, "_typ") in comp
1313

pandas/core/frame.py

+16-5
Original file line numberDiff line numberDiff line change
@@ -2164,10 +2164,14 @@ def to_stata(
21642164
from pandas.io.stata import StataWriter as statawriter
21652165
elif version == 117:
21662166
# mypy: Name 'statawriter' already defined (possibly by an import)
2167-
from pandas.io.stata import StataWriter117 as statawriter # type: ignore
2167+
from pandas.io.stata import ( # type: ignore[no-redef]
2168+
StataWriter117 as statawriter,
2169+
)
21682170
else: # versions 118 and 119
21692171
# mypy: Name 'statawriter' already defined (possibly by an import)
2170-
from pandas.io.stata import StataWriterUTF8 as statawriter # type: ignore
2172+
from pandas.io.stata import ( # type: ignore[no-redef]
2173+
StataWriterUTF8 as statawriter,
2174+
)
21712175

21722176
kwargs: Dict[str, Any] = {}
21732177
if version is None or version >= 117:
@@ -2178,7 +2182,7 @@ def to_stata(
21782182
kwargs["version"] = version
21792183

21802184
# mypy: Too many arguments for "StataWriter"
2181-
writer = statawriter( # type: ignore
2185+
writer = statawriter( # type: ignore[call-arg]
21822186
path,
21832187
self,
21842188
convert_dates=convert_dates,
@@ -3578,7 +3582,13 @@ def extract_unique_dtypes_from_dtypes_set(
35783582
extracted_dtypes = [
35793583
unique_dtype
35803584
for unique_dtype in unique_dtypes
3581-
if issubclass(unique_dtype.type, tuple(dtypes_set)) # type: ignore
3585+
# error: Argument 1 to "tuple" has incompatible type
3586+
# "FrozenSet[Union[ExtensionDtype, str, Any, Type[str],
3587+
# Type[float], Type[int], Type[complex], Type[bool]]]";
3588+
# expected "Iterable[Union[type, Tuple[Any, ...]]]"
3589+
if issubclass(
3590+
unique_dtype.type, tuple(dtypes_set) # type: ignore[arg-type]
3591+
)
35823592
]
35833593
return extracted_dtypes
35843594

@@ -5250,7 +5260,8 @@ def f(vals):
52505260
# TODO: Just move the sort_values doc here.
52515261
@Substitution(**_shared_doc_kwargs)
52525262
@Appender(NDFrame.sort_values.__doc__)
5253-
def sort_values( # type: ignore[override] # NOQA # issue 27237
5263+
# error: Signature of "sort_values" incompatible with supertype "NDFrame"
5264+
def sort_values( # type: ignore[override]
52545265
self,
52555266
by,
52565267
axis=0,

pandas/core/generic.py

+13-5
Original file line numberDiff line numberDiff line change
@@ -589,9 +589,9 @@ def swapaxes(self: FrameOrSeries, axis1, axis2, copy=True) -> FrameOrSeries:
589589

590590
# ignore needed because of NDFrame constructor is different than
591591
# DataFrame/Series constructors.
592-
return self._constructor(new_values, *new_axes).__finalize__( # type: ignore
593-
self, method="swapaxes"
594-
)
592+
return self._constructor(
593+
new_values, *new_axes # type: ignore[arg-type]
594+
).__finalize__(self, method="swapaxes")
595595

596596
def droplevel(self: FrameOrSeries, level, axis=0) -> FrameOrSeries:
597597
"""
@@ -4011,7 +4011,11 @@ def add_prefix(self: FrameOrSeries, prefix: str) -> FrameOrSeries:
40114011
f = functools.partial("{prefix}{}".format, prefix=prefix)
40124012

40134013
mapper = {self._info_axis_name: f}
4014-
return self.rename(**mapper) # type: ignore
4014+
# error: Incompatible return value type (got "Optional[FrameOrSeries]",
4015+
# expected "FrameOrSeries")
4016+
# error: Argument 1 to "rename" of "NDFrame" has incompatible type
4017+
# "**Dict[str, partial[str]]"; expected "Union[str, int, None]"
4018+
return self.rename(**mapper) # type: ignore[return-value, arg-type]
40154019

40164020
def add_suffix(self: FrameOrSeries, suffix: str) -> FrameOrSeries:
40174021
"""
@@ -4070,7 +4074,11 @@ def add_suffix(self: FrameOrSeries, suffix: str) -> FrameOrSeries:
40704074
f = functools.partial("{}{suffix}".format, suffix=suffix)
40714075

40724076
mapper = {self._info_axis_name: f}
4073-
return self.rename(**mapper) # type: ignore
4077+
# error: Incompatible return value type (got "Optional[FrameOrSeries]",
4078+
# expected "FrameOrSeries")
4079+
# error: Argument 1 to "rename" of "NDFrame" has incompatible type
4080+
# "**Dict[str, partial[str]]"; expected "Union[str, int, None]"
4081+
return self.rename(**mapper) # type: ignore[return-value, arg-type]
40744082

40754083
def sort_values(
40764084
self,

pandas/core/indexes/base.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -885,7 +885,8 @@ def _format_data(self, name=None) -> str_t:
885885
if self.inferred_type == "string":
886886
is_justify = False
887887
elif self.inferred_type == "categorical":
888-
if is_object_dtype(self.categories): # type: ignore
888+
# error: "Index" has no attribute "categories"
889+
if is_object_dtype(self.categories): # type: ignore[attr-defined]
889890
is_justify = False
890891

891892
return format_object_summary(
@@ -940,7 +941,8 @@ def _format_with_header(self, header, na_rep="NaN") -> List[str_t]:
940941
if mask.any():
941942
result = np.array(result)
942943
result[mask] = na_rep
943-
result = result.tolist() # type: ignore
944+
# error: "List[str]" has no attribute "tolist"
945+
result = result.tolist() # type: ignore[attr-defined]
944946
else:
945947
result = trim_front(format_array(values, None, justify="left"))
946948
return header + result

pandas/core/indexes/datetimelike.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,8 @@ def _join_i8_wrapper(joinf, with_indexers: bool = True):
5454
Create the join wrapper methods.
5555
"""
5656

57-
@staticmethod # type: ignore
57+
# error: 'staticmethod' used with a non-method
58+
@staticmethod # type: ignore[misc]
5859
def wrapper(left, right):
5960
if isinstance(left, (np.ndarray, ABCIndex, ABCSeries, DatetimeLikeArrayMixin)):
6061
left = left.view("i8")
@@ -95,7 +96,10 @@ class DatetimeIndexOpsMixin(ExtensionIndex):
9596
_bool_ops: List[str] = []
9697
_field_ops: List[str] = []
9798

98-
hasnans = cache_readonly(DatetimeLikeArrayMixin._hasnans.fget) # type: ignore
99+
# error: "Callable[[Any], Any]" has no attribute "fget"
100+
hasnans = cache_readonly(
101+
DatetimeLikeArrayMixin._hasnans.fget # type: ignore[attr-defined]
102+
)
99103
_hasnans = hasnans # for index / array -agnostic code
100104

101105
@property

pandas/core/internals/blocks.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -2744,7 +2744,8 @@ def _block_shape(values: ArrayLike, ndim: int = 1) -> ArrayLike:
27442744
# TODO(EA2D): https://github.com/pandas-dev/pandas/issues/23023
27452745
# block.shape is incorrect for "2D" ExtensionArrays
27462746
# We can't, and don't need to, reshape.
2747-
values = values.reshape(tuple((1,) + shape)) # type: ignore
2747+
# error: "ExtensionArray" has no attribute "reshape"
2748+
values = values.reshape(tuple((1,) + shape)) # type: ignore[attr-defined]
27482749
return values
27492750

27502751

pandas/core/ops/array_ops.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,8 @@ def fill_bool(x, left=None):
349349
filler = fill_int if is_self_int_dtype and is_other_int_dtype else fill_bool
350350

351351
res_values = na_logical_op(lvalues, rvalues, op)
352-
res_values = filler(res_values) # type: ignore
352+
# error: Cannot call function of unknown type
353+
res_values = filler(res_values) # type: ignore[operator]
353354

354355
return res_values
355356

pandas/core/resample.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -967,7 +967,7 @@ def __init__(self, obj, *args, **kwargs):
967967
setattr(self, attr, kwargs.get(attr, getattr(parent, attr)))
968968

969969
# error: Too many arguments for "__init__" of "object"
970-
super().__init__(None) # type: ignore
970+
super().__init__(None) # type: ignore[call-arg]
971971
self._groupby = groupby
972972
self._groupby.mutated = True
973973
self._groupby.grouper.mutated = True

pandas/core/series.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -571,7 +571,8 @@ def _values(self):
571571
"""
572572
return self._mgr.internal_values()
573573

574-
@Appender(base.IndexOpsMixin.array.__doc__) # type: ignore
574+
# error: Decorated property not supported
575+
@Appender(base.IndexOpsMixin.array.__doc__) # type: ignore[misc]
575576
@property
576577
def array(self) -> ExtensionArray:
577578
return self._mgr._block.array_values()
@@ -4921,7 +4922,10 @@ def to_timestamp(self, freq=None, how="start", copy=True) -> "Series":
49214922

49224923
if not isinstance(self.index, PeriodIndex):
49234924
raise TypeError(f"unsupported Type {type(self.index).__name__}")
4924-
new_index = self.index.to_timestamp(freq=freq, how=how) # type: ignore
4925+
# error: "PeriodIndex" has no attribute "to_timestamp"
4926+
new_index = self.index.to_timestamp( # type: ignore[attr-defined]
4927+
freq=freq, how=how
4928+
)
49254929
return self._constructor(new_values, index=new_index).__finalize__(
49264930
self, method="to_timestamp"
49274931
)

pandas/core/tools/datetimes.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,7 @@ def _convert_listlike_datetimes(
309309
if tz == "utc":
310310
# error: Item "DatetimeIndex" of "Union[DatetimeArray, DatetimeIndex]" has
311311
# no attribute "tz_convert"
312-
arg = arg.tz_convert(None).tz_localize(tz) # type: ignore
312+
arg = arg.tz_convert(None).tz_localize(tz) # type: ignore[union-attr]
313313
return arg
314314

315315
elif is_datetime64_ns_dtype(arg_dtype):

0 commit comments

Comments
 (0)