Skip to content

TYP: tidy comments for # type: ignore #39794

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
2 changes: 1 addition & 1 deletion pandas/_testing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,7 @@ def makeCustomIndex(
"p": makePeriodIndex,
}.get(idx_type)
if idx_func:
# pandas\_testing.py:2120: error: Cannot call function of unknown type
# error: Cannot call function of unknown type
idx = idx_func(nentries) # type: ignore[operator]
# but we need to fill in the name
if names:
Expand Down
8 changes: 3 additions & 5 deletions pandas/_testing/_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,8 @@ def dec(f):
is_decorating = not kwargs and len(args) == 1 and callable(args[0])
if is_decorating:
f = args[0]
# pandas\_testing.py:2331: error: Incompatible types in assignment
# (expression has type "List[<nothing>]", variable has type
# "Tuple[Any, ...]")
# error: Incompatible types in assignment (expression has type
# "List[<nothing>]", variable has type "Tuple[Any, ...]")
args = [] # type: ignore[assignment]
return dec(f)
else:
Expand Down Expand Up @@ -205,8 +204,7 @@ def wrapper(*args, **kwargs):
except Exception as err:
errno = getattr(err, "errno", None)
if not errno and hasattr(errno, "reason"):
# pandas\_testing.py:2521: error: "Exception" has no attribute
# "reason"
# error: "Exception" has no attribute "reason"
errno = getattr(err.reason, "errno", None) # type: ignore[attr-defined]

if errno in skip_errnos:
Expand Down
13 changes: 5 additions & 8 deletions pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -445,8 +445,7 @@ def _validate_comparison_value(self, other):
raise InvalidComparison(other)

if isinstance(other, self._recognized_scalars) or other is NaT:
# pandas\core\arrays\datetimelike.py:432: error: Too many arguments
# for "object" [call-arg]
# error: Too many arguments for "object"
other = self._scalar_type(other) # type: ignore[call-arg]
try:
self._check_compatible_with(other)
Expand Down Expand Up @@ -497,17 +496,15 @@ def _validate_shift_value(self, fill_value):
if is_valid_na_for_dtype(fill_value, self.dtype):
fill_value = NaT
elif isinstance(fill_value, self._recognized_scalars):
# pandas\core\arrays\datetimelike.py:746: error: Too many arguments
# for "object" [call-arg]
# error: Too many arguments for "object"
fill_value = self._scalar_type(fill_value) # type: ignore[call-arg]
else:
# only warn if we're not going to raise
if self._scalar_type is Period and lib.is_integer(fill_value):
# kludge for #31971 since Period(integer) tries to cast to str
new_fill = Period._from_ordinal(fill_value, freq=self.freq)
else:
# pandas\core\arrays\datetimelike.py:753: error: Too many
# arguments for "object" [call-arg]
# error: Too many arguments for "object"
new_fill = self._scalar_type(fill_value) # type: ignore[call-arg]

# stacklevel here is chosen to be correct when called from
Expand Down Expand Up @@ -563,7 +560,7 @@ def _validate_scalar(
value = NaT

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

else:
Expand Down Expand Up @@ -1679,7 +1676,7 @@ def factorize(self, na_sentinel=-1, sort: bool = False):
# TODO: overload __getitem__, a slice indexer returns same type as self
# error: Incompatible types in assignment (expression has type
# "Union[DatetimeLikeArrayMixin, Union[Any, Any]]", variable
# has type "TimelikeOps") [assignment]
# has type "TimelikeOps")
uniques = uniques[::-1] # type: ignore[assignment]
return codes, uniques
# FIXME: shouldn't get here; we are ignoring sort
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -1508,7 +1508,7 @@ def isin(self, values) -> np.ndarray:
# GH#38353 instead of casting to object, operating on a
# complex128 ndarray is much more performant.

# error: "ArrayLike" has no attribute "view" [attr-defined]
# error: "ArrayLike" has no attribute "view"
left = self._combined.view("complex128") # type:ignore[attr-defined]
right = values._combined.view("complex128")
return np.in1d(left, right)
Expand Down
5 changes: 2 additions & 3 deletions pandas/core/arrays/string_.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,9 +190,8 @@ def __init__(self, values, copy=False):
values = extract_array(values)

super().__init__(values, copy=copy)
# pandas\core\arrays\string_.py:188: error: Incompatible types in
# assignment (expression has type "StringDtype", variable has type
# "PandasDtype") [assignment]
# error: Incompatible types in assignment (expression has type "StringDtype",
# variable has type "PandasDtype")
self._dtype = StringDtype() # type: ignore[assignment]
if not isinstance(values, type(self)):
self._validate()
Expand Down
63 changes: 22 additions & 41 deletions pandas/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,7 @@ def __sizeof__(self):
either a value or Series of values
"""
if hasattr(self, "memory_usage"):
# pandas\core\base.py:84: error: "PandasObject" has no attribute
# "memory_usage" [attr-defined]
# error: "PandasObject" has no attribute "memory_usage"
mem = self.memory_usage(deep=True) # type: ignore[attr-defined]
return int(mem if is_scalar(mem) else mem.sum())

Expand Down Expand Up @@ -206,17 +205,14 @@ def _selection_list(self):

@cache_readonly
def _selected_obj(self):
# pandas\core\base.py:195: error: "SelectionMixin" has no attribute
# "obj" [attr-defined]
# error: "SelectionMixin" has no attribute "obj"
if self._selection is None or isinstance(
self.obj, ABCSeries # type: ignore[attr-defined]
):
# pandas\core\base.py:194: error: "SelectionMixin" has no attribute
# "obj" [attr-defined]
# error: "SelectionMixin" has no attribute "obj"
return self.obj # type: ignore[attr-defined]
else:
# pandas\core\base.py:204: error: "SelectionMixin" has no attribute
# "obj" [attr-defined]
# error: "SelectionMixin" has no attribute "obj"
return self.obj[self._selection] # type: ignore[attr-defined]

@cache_readonly
Expand All @@ -225,57 +221,48 @@ def ndim(self) -> int:

@cache_readonly
def _obj_with_exclusions(self):
# pandas\core\base.py:209: error: "SelectionMixin" has no attribute
# "obj" [attr-defined]
# error: "SelectionMixin" has no attribute "obj"
if self._selection is not None and isinstance(
self.obj, ABCDataFrame # type: ignore[attr-defined]
):
# pandas\core\base.py:217: error: "SelectionMixin" has no attribute
# "obj" [attr-defined]
# error: "SelectionMixin" has no attribute "obj"
return self.obj.reindex( # type: ignore[attr-defined]
columns=self._selection_list
)

# pandas\core\base.py:207: error: "SelectionMixin" has no attribute
# "exclusions" [attr-defined]
# error: "SelectionMixin" has no attribute "exclusions"
if len(self.exclusions) > 0: # type: ignore[attr-defined]
# pandas\core\base.py:208: error: "SelectionMixin" has no attribute
# "obj" [attr-defined]

# pandas\core\base.py:208: error: "SelectionMixin" has no attribute
# "exclusions" [attr-defined]
# error: "SelectionMixin" has no attribute "obj"
# error: "SelectionMixin" has no attribute "exclusions"
return self.obj.drop(self.exclusions, axis=1) # type: ignore[attr-defined]
else:
# pandas\core\base.py:210: error: "SelectionMixin" has no attribute
# "obj" [attr-defined]
# error: "SelectionMixin" has no attribute "obj"
return self.obj # type: ignore[attr-defined]

def __getitem__(self, key):
if self._selection is not None:
raise IndexError(f"Column(s) {self._selection} already selected")

if isinstance(key, (list, tuple, ABCSeries, ABCIndex, np.ndarray)):
# pandas\core\base.py:217: error: "SelectionMixin" has no attribute
# "obj" [attr-defined]
# error: "SelectionMixin" has no attribute "obj"
if len(
self.obj.columns.intersection(key) # type: ignore[attr-defined]
) != len(key):
# pandas\core\base.py:218: error: "SelectionMixin" has no
# attribute "obj" [attr-defined]
# error: "SelectionMixin" has no attribute "obj"
bad_keys = list(
set(key).difference(self.obj.columns) # type: ignore[attr-defined]
)
raise KeyError(f"Columns not found: {str(bad_keys)[1:-1]}")
return self._gotitem(list(key), ndim=2)

elif not getattr(self, "as_index", False):
# error: "SelectionMixin" has no attribute "obj" [attr-defined]
# error: "SelectionMixin" has no attribute "obj"
if key not in self.obj.columns: # type: ignore[attr-defined]
raise KeyError(f"Column not found: {key}")
return self._gotitem(key, ndim=2)

else:
# error: "SelectionMixin" has no attribute "obj" [attr-defined]
# error: "SelectionMixin" has no attribute "obj"
if key not in self.obj: # type: ignore[attr-defined]
raise KeyError(f"Column not found: {key}")
return self._gotitem(key, ndim=1)
Expand Down Expand Up @@ -601,8 +588,7 @@ def to_numpy(
dtype='datetime64[ns]')
"""
if is_extension_array_dtype(self.dtype):
# pandas\core\base.py:837: error: Too many arguments for "to_numpy"
# of "ExtensionArray" [call-arg]
# error: Too many arguments for "to_numpy" of "ExtensionArray"
return self.array.to_numpy( # type: ignore[call-arg]
dtype, copy=copy, na_value=na_value, **kwargs
)
Expand Down Expand Up @@ -914,13 +900,11 @@ def _map_values(self, mapper, na_action=None):
# use the built in categorical series mapper which saves
# time by mapping the categories instead of all values

# pandas\core\base.py:893: error: Incompatible types in
# assignment (expression has type "Categorical", variable has
# type "IndexOpsMixin") [assignment]
# error: Incompatible types in assignment (expression has type
# "Categorical", variable has type "IndexOpsMixin")
self = cast("Categorical", self) # type: ignore[assignment]
# pandas\core\base.py:894: error: Item "ExtensionArray" of
# "Union[ExtensionArray, Any]" has no attribute "map"
# [union-attr]
# error: Item "ExtensionArray" of "Union[ExtensionArray, Any]" has no
# attribute "map"
return self._values.map(mapper) # type: ignore[union-attr]

values = self._values
Expand All @@ -938,8 +922,7 @@ def _map_values(self, mapper, na_action=None):
raise NotImplementedError
map_f = lambda values, f: values.map(f)
else:
# pandas\core\base.py:1142: error: "IndexOpsMixin" has no attribute
# "astype" [attr-defined]
# error: "IndexOpsMixin" has no attribute "astype"
values = self.astype(object)._values # type: ignore[attr-defined]
if na_action == "ignore":
map_f = lambda values, f: lib.map_infer_mask(
Expand Down Expand Up @@ -1177,8 +1160,7 @@ def memory_usage(self, deep=False):
are not components of the array if deep=False or if used on PyPy
"""
if hasattr(self.array, "memory_usage"):
# pandas\core\base.py:1379: error: "ExtensionArray" has no
# attribute "memory_usage" [attr-defined]
# error: "ExtensionArray" has no attribute "memory_usage"
return self.array.memory_usage(deep=deep) # type: ignore[attr-defined]

v = self.array.nbytes
Expand Down Expand Up @@ -1313,8 +1295,7 @@ def searchsorted(self, value, side="left", sorter=None) -> np.ndarray:

def drop_duplicates(self, keep="first"):
duplicated = self.duplicated(keep=keep)
# pandas\core\base.py:1507: error: Value of type "IndexOpsMixin" is not
# indexable [index]
# error: Value of type "IndexOpsMixin" is not indexable
return self[~duplicated] # type: ignore[index]

def duplicated(self, keep="first"):
Expand Down
4 changes: 0 additions & 4 deletions pandas/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,10 +268,6 @@ def maybe_iterable_to_list(obj: Union[Iterable[T], T]) -> Union[Collection[T], T
"""
if isinstance(obj, abc.Iterable) and not isinstance(obj, abc.Sized):
return list(obj)
# error: Incompatible return value type (got
# "Union[pandas.core.common.<subclass of "Iterable" and "Sized">,
# pandas.core.common.<subclass of "Iterable" and "Sized">1, T]", expected
# "Union[Collection[T], T]") [return-value]
obj = cast(Collection, obj)
return obj

Expand Down
6 changes: 2 additions & 4 deletions pandas/core/computation/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -659,8 +659,7 @@ def visit_Call(self, node, side=None, **kwargs):
raise

if res is None:
# pandas\core\computation\expr.py:663: error: "expr" has no
# attribute "id" [attr-defined]
# error: "expr" has no attribute "id"
raise ValueError(
f"Invalid function call {node.func.id}" # type: ignore[attr-defined]
)
Expand All @@ -684,8 +683,7 @@ def visit_Call(self, node, side=None, **kwargs):

for key in node.keywords:
if not isinstance(key, ast.keyword):
# pandas\core\computation\expr.py:684: error: "expr" has no
# attribute "id" [attr-defined]
# error: "expr" has no attribute "id"
raise ValueError(
"keyword error in function call " # type: ignore[attr-defined]
f"'{node.func.id}'"
Expand Down
5 changes: 2 additions & 3 deletions pandas/core/computation/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,7 @@ def __init__(self, name: str, is_local: Optional[bool] = None):
class Term:
def __new__(cls, name, env, side=None, encoding=None):
klass = Constant if not isinstance(name, str) else cls
# pandas\core\computation\ops.py:72: error: Argument 2 for "super" not
# an instance of argument 1 [misc]
# error: Argument 2 for "super" not an instance of argument 1
supr_new = super(Term, klass).__new__ # type: ignore[misc]
return supr_new(klass)

Expand Down Expand Up @@ -593,7 +592,7 @@ def __init__(self, func, args):
self.func = func

def __call__(self, env):
# pandas\core\computation\ops.py:592: error: "Op" not callable [operator]
# error: "Op" not callable
operands = [op(env) for op in self.operands] # type: ignore[operator]
with np.errstate(all="ignore"):
return self.func.func(*operands)
Expand Down
34 changes: 12 additions & 22 deletions pandas/core/computation/scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,17 +131,14 @@ def __init__(
# scope when we align terms (alignment accesses the underlying
# numpy array of pandas objects)

# pandas\core\computation\scope.py:132: error: Incompatible types
# in assignment (expression has type "ChainMap[str, Any]", variable
# has type "DeepChainMap[str, Any]") [assignment]
# error: Incompatible types in assignment (expression has type
# "ChainMap[str, Any]", variable has type "DeepChainMap[str, Any]")
self.scope = self.scope.new_child( # type: ignore[assignment]
(global_dict or frame.f_globals).copy()
)
if not isinstance(local_dict, Scope):
# pandas\core\computation\scope.py:134: error: Incompatible
# types in assignment (expression has type "ChainMap[str,
# Any]", variable has type "DeepChainMap[str, Any]")
# [assignment]
# error: Incompatible types in assignment (expression has type
# "ChainMap[str, Any]", variable has type "DeepChainMap[str, Any]")
self.scope = self.scope.new_child( # type: ignore[assignment]
(local_dict or frame.f_locals).copy()
)
Expand All @@ -150,8 +147,7 @@ def __init__(

# assumes that resolvers are going from outermost scope to inner
if isinstance(local_dict, Scope):
# pandas\core\computation\scope.py:140: error: Cannot determine
# type of 'resolvers' [has-type]
# error: Cannot determine type of 'resolvers'
resolvers += tuple(local_dict.resolvers.maps) # type: ignore[has-type]
self.resolvers = DeepChainMap(*resolvers)
self.temps = {}
Expand Down Expand Up @@ -239,8 +235,7 @@ def swapkey(self, old_key: str, new_key: str, new_value=None):

for mapping in maps:
if old_key in mapping:
# pandas\core\computation\scope.py:228: error: Unsupported
# target for indexed assignment ("Mapping[Any, Any]") [index]
# error: Unsupported target for indexed assignment ("Mapping[Any, Any]")
mapping[new_key] = new_value # type: ignore[index]
return

Expand All @@ -260,10 +255,8 @@ def _get_vars(self, stack, scopes: List[str]):
for scope, (frame, _, _, _, _, _) in variables:
try:
d = getattr(frame, "f_" + scope)
# pandas\core\computation\scope.py:247: error: Incompatible
# types in assignment (expression has type "ChainMap[str,
# Any]", variable has type "DeepChainMap[str, Any]")
# [assignment]
# error: Incompatible types in assignment (expression has type
# "ChainMap[str, Any]", variable has type "DeepChainMap[str, Any]")
self.scope = self.scope.new_child(d) # type: ignore[assignment]
finally:
# won't remove it, but DECREF it
Expand Down Expand Up @@ -331,13 +324,10 @@ def full_scope(self):
vars : DeepChainMap
All variables in this scope.
"""
# pandas\core\computation\scope.py:314: error: Unsupported operand
# types for + ("List[Dict[Any, Any]]" and "List[Mapping[Any, Any]]")
# [operator]

# pandas\core\computation\scope.py:314: error: Unsupported operand
# types for + ("List[Dict[Any, Any]]" and "List[Mapping[str, Any]]")
# [operator]
# error: Unsupported operand types for + ("List[Dict[Any, Any]]" and
# "List[Mapping[Any, Any]]")
# error: Unsupported operand types for + ("List[Dict[Any, Any]]" and
# "List[Mapping[str, Any]]")
maps = (
[self.temps]
+ self.resolvers.maps # type: ignore[operator]
Expand Down
Loading