diff --git a/pandas/_testing.py b/pandas/_testing.py index ded2ed3141b47..5dcd1247e52ba 100644 --- a/pandas/_testing.py +++ b/pandas/_testing.py @@ -117,14 +117,24 @@ def set_testing_mode(): # set the testing mode filters testing_mode = os.environ.get("PANDAS_TESTING_MODE", "None") if "deprecate" in testing_mode: - warnings.simplefilter("always", _testing_mode_warnings) + # pandas\_testing.py:119: error: Argument 2 to "simplefilter" has + # incompatible type "Tuple[Type[DeprecationWarning], + # Type[ResourceWarning]]"; expected "Type[Warning]" + warnings.simplefilter( + "always", _testing_mode_warnings # type: ignore[arg-type] + ) def reset_testing_mode(): # reset the testing mode filters testing_mode = os.environ.get("PANDAS_TESTING_MODE", "None") if "deprecate" in testing_mode: - warnings.simplefilter("ignore", _testing_mode_warnings) + # pandas\_testing.py:126: error: Argument 2 to "simplefilter" has + # incompatible type "Tuple[Type[DeprecationWarning], + # Type[ResourceWarning]]"; expected "Type[Warning]" + warnings.simplefilter( + "ignore", _testing_mode_warnings # type: ignore[arg-type] + ) set_testing_mode() @@ -241,16 +251,22 @@ def decompress_file(path, compression): if compression is None: f = open(path, "rb") elif compression == "gzip": - f = gzip.open(path, "rb") + # pandas\_testing.py:243: error: Incompatible types in assignment + # (expression has type "IO[Any]", variable has type "BinaryIO") + f = gzip.open(path, "rb") # type: ignore[assignment] elif compression == "bz2": - f = bz2.BZ2File(path, "rb") + # pandas\_testing.py:245: error: Incompatible types in assignment + # (expression has type "BZ2File", variable has type "BinaryIO") + f = bz2.BZ2File(path, "rb") # type: ignore[assignment] elif compression == "xz": f = get_lzma_file(lzma)(path, "rb") elif compression == "zip": zip_file = zipfile.ZipFile(path) zip_names = zip_file.namelist() if len(zip_names) == 1: - f = zip_file.open(zip_names.pop()) + # pandas\_testing.py:252: error: Incompatible types in assignment + # (expression has type "IO[bytes]", variable has type "BinaryIO") + f = zip_file.open(zip_names.pop()) # type: ignore[assignment] else: raise ValueError(f"ZIP file {path} error. Only one file per ZIP.") else: @@ -286,9 +302,15 @@ def write_to_compressed(compression, path, data, dest="test"): if compression == "zip": compress_method = zipfile.ZipFile elif compression == "gzip": - compress_method = gzip.GzipFile + # pandas\_testing.py:288: error: Incompatible types in assignment + # (expression has type "Type[GzipFile]", variable has type + # "Type[ZipFile]") + compress_method = gzip.GzipFile # type: ignore[assignment] elif compression == "bz2": - compress_method = bz2.BZ2File + # pandas\_testing.py:290: error: Incompatible types in assignment + # (expression has type "Type[BZ2File]", variable has type + # "Type[ZipFile]") + compress_method = bz2.BZ2File # type: ignore[assignment] elif compression == "xz": compress_method = get_lzma_file(lzma) else: @@ -300,7 +322,10 @@ def write_to_compressed(compression, path, data, dest="test"): method = "writestr" else: mode = "wb" - args = (data,) + # pandas\_testing.py:302: error: Incompatible types in assignment + # (expression has type "Tuple[Any]", variable has type "Tuple[Any, + # Any]") + args = (data,) # type: ignore[assignment] method = "write" with compress_method(path, mode=mode) as f: @@ -1996,7 +2021,8 @@ def all_timeseries_index_generator(k=10): """ make_index_funcs = [makeDateIndex, makePeriodIndex, makeTimedeltaIndex] for make_index_func in make_index_funcs: - yield make_index_func(k=k) + # pandas\_testing.py:1986: error: Cannot call function of unknown type + yield make_index_func(k=k) # type: ignore[operator] # make series @@ -2130,7 +2156,8 @@ def makeCustomIndex( p=makePeriodIndex, ).get(idx_type) if idx_func: - idx = idx_func(nentries) + # pandas\_testing.py:2120: error: Cannot call function of unknown type + idx = idx_func(nentries) # type: ignore[operator] # but we need to fill in the name if names: idx.name = names[0] @@ -2158,7 +2185,8 @@ def keyfunc(x): # build a list of lists to create the index from div_factor = nentries // ndupe_l[i] + 1 - cnt = Counter() + # pandas\_testing.py:2148: error: Need type annotation for 'cnt' + cnt = Counter() # type: ignore[var-annotated] for j in range(div_factor): label = f"{prefix}_l{i}_g{j}" cnt[label] = ndupe_l[i] @@ -2316,7 +2344,14 @@ def _gen_unique_rand(rng, _extra_size): def makeMissingDataframe(density=0.9, random_state=None): df = makeDataFrame() - i, j = _create_missing_idx(*df.shape, density=density, random_state=random_state) + # pandas\_testing.py:2306: error: "_create_missing_idx" gets multiple + # values for keyword argument "density" [misc] + + # pandas\_testing.py:2306: error: "_create_missing_idx" gets multiple + # values for keyword argument "random_state" [misc] + i, j = _create_missing_idx( # type: ignore[misc] + *df.shape, density=density, random_state=random_state + ) df.values[i, j] = np.nan return df @@ -2341,7 +2376,10 @@ def dec(f): is_decorating = not kwargs and len(args) == 1 and callable(args[0]) if is_decorating: f = args[0] - args = [] + # pandas\_testing.py:2331: error: Incompatible types in assignment + # (expression has type "List[]", variable has type + # "Tuple[Any, ...]") + args = [] # type: ignore[assignment] return dec(f) else: return dec @@ -2534,7 +2572,9 @@ def wrapper(*args, **kwargs): except Exception as err: errno = getattr(err, "errno", None) if not errno and hasattr(errno, "reason"): - errno = getattr(err.reason, "errno", None) + # pandas\_testing.py:2521: error: "Exception" has no attribute + # "reason" + errno = getattr(err.reason, "errno", None) # type: ignore[attr-defined] if errno in skip_errnos: skip(f"Skipping test due to known errno and error {err}") diff --git a/pandas/core/apply.py b/pandas/core/apply.py index a14debce6eea7..fa4fbe711fbe4 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -141,7 +141,11 @@ def get_result(self): """ compute the results """ # dispatch to agg if is_list_like(self.f) or is_dict_like(self.f): - return self.obj.aggregate(self.f, axis=self.axis, *self.args, **self.kwds) + # pandas\core\apply.py:144: error: "aggregate" of "DataFrame" gets + # multiple values for keyword argument "axis" + return self.obj.aggregate( # type: ignore[misc] + self.f, axis=self.axis, *self.args, **self.kwds + ) # all empty if len(self.columns) == 0 and len(self.index) == 0: diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 8d90035491d28..f2f843886e802 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -431,7 +431,9 @@ def _validate_comparison_value(self, other): raise InvalidComparison(other) if isinstance(other, self._recognized_scalars) or other is NaT: - other = self._scalar_type(other) + # pandas\core\arrays\datetimelike.py:432: error: Too many arguments + # for "object" [call-arg] + other = self._scalar_type(other) # type: ignore[call-arg] try: self._check_compatible_with(other) except TypeError as err: @@ -491,14 +493,18 @@ def _validate_shift_value(self, fill_value): if is_valid_nat_for_dtype(fill_value, self.dtype): fill_value = NaT elif isinstance(fill_value, self._recognized_scalars): - fill_value = self._scalar_type(fill_value) + # pandas\core\arrays\datetimelike.py:746: error: Too many arguments + # for "object" [call-arg] + 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: - new_fill = self._scalar_type(fill_value) + # pandas\core\arrays\datetimelike.py:753: error: Too many + # arguments for "object" [call-arg] + new_fill = self._scalar_type(fill_value) # type: ignore[call-arg] # stacklevel here is chosen to be correct when called from # DataFrame.shift or Series.shift diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py index c73855f281bcc..3b297e7c2b13b 100644 --- a/pandas/core/arrays/string_.py +++ b/pandas/core/arrays/string_.py @@ -186,7 +186,10 @@ def __init__(self, values, copy=False): values = extract_array(values) super().__init__(values, copy=copy) - self._dtype = StringDtype() + # pandas\core\arrays\string_.py:188: error: Incompatible types in + # assignment (expression has type "StringDtype", variable has type + # "PandasDtype") [assignment] + self._dtype = StringDtype() # type: ignore[assignment] if not isinstance(values, type(self)): self._validate() diff --git a/pandas/core/base.py b/pandas/core/base.py index b979298fa53f6..0f6c369f5e19b 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -95,7 +95,9 @@ def __sizeof__(self): either a value or Series of values """ if hasattr(self, "memory_usage"): - mem = self.memory_usage(deep=True) + # pandas\core\base.py:84: error: "PandasObject" has no attribute + # "memory_usage" [attr-defined] + mem = self.memory_usage(deep=True) # type: ignore[attr-defined] return int(mem if is_scalar(mem) else mem.sum()) # no memory_usage attribute, so fall back to object's 'sizeof' @@ -204,10 +206,18 @@ def _selection_list(self): @cache_readonly def _selected_obj(self): - if self._selection is None or isinstance(self.obj, ABCSeries): - return self.obj + # pandas\core\base.py:195: error: "SelectionMixin" has no attribute + # "obj" [attr-defined] + 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] + return self.obj # type: ignore[attr-defined] else: - return self.obj[self._selection] + # pandas\core\base.py:204: error: "SelectionMixin" has no attribute + # "obj" [attr-defined] + return self.obj[self._selection] # type: ignore[attr-defined] @cache_readonly def ndim(self) -> int: @@ -215,21 +225,46 @@ def ndim(self) -> int: @cache_readonly def _obj_with_exclusions(self): - if self._selection is not None and isinstance(self.obj, ABCDataFrame): - return self.obj.reindex(columns=self._selection_list) + # pandas\core\base.py:209: error: "SelectionMixin" has no attribute + # "obj" [attr-defined] + 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] + 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] + if len(self.exclusions) > 0: # type: ignore[attr-defined] + # pandas\core\base.py:208: error: "SelectionMixin" has no attribute + # "obj" [attr-defined] - if len(self.exclusions) > 0: - return self.obj.drop(self.exclusions, axis=1) + # pandas\core\base.py:208: error: "SelectionMixin" has no attribute + # "exclusions" [attr-defined] + return self.obj.drop(self.exclusions, axis=1) # type: ignore[attr-defined] else: - return self.obj + # pandas\core\base.py:210: error: "SelectionMixin" has no attribute + # "obj" [attr-defined] + 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, ABCIndexClass, np.ndarray)): - if len(self.obj.columns.intersection(key)) != len(key): - bad_keys = list(set(key).difference(self.obj.columns)) + # pandas\core\base.py:217: error: "SelectionMixin" has no attribute + # "obj" [attr-defined] + 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] + 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) @@ -559,7 +594,11 @@ def to_numpy(self, dtype=None, copy=False, na_value=lib.no_default, **kwargs): dtype='datetime64[ns]') """ if is_extension_array_dtype(self.dtype): - return self.array.to_numpy(dtype, copy=copy, na_value=na_value, **kwargs) + # pandas\core\base.py:837: error: Too many arguments for "to_numpy" + # of "ExtensionArray" [call-arg] + return self.array.to_numpy( # type: ignore[call-arg] + dtype, copy=copy, na_value=na_value, **kwargs + ) elif kwargs: bad_keys = list(kwargs.keys())[0] raise TypeError( @@ -851,8 +890,15 @@ def _map_values(self, mapper, na_action=None): if is_categorical_dtype(self.dtype): # use the built in categorical series mapper which saves # time by mapping the categories instead of all values - self = cast("Categorical", self) - return self._values.map(mapper) + + # pandas\core\base.py:893: error: Incompatible types in + # assignment (expression has type "Categorical", variable has + # type "IndexOpsMixin") [assignment] + 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] + return self._values.map(mapper) # type: ignore[union-attr] values = self._values @@ -869,7 +915,9 @@ def _map_values(self, mapper, na_action=None): raise NotImplementedError map_f = lambda values, f: values.map(f) else: - values = self.astype(object)._values + # pandas\core\base.py:1142: error: "IndexOpsMixin" has no attribute + # "astype" [attr-defined] + values = self.astype(object)._values # type: ignore[attr-defined] if na_action == "ignore": def map_f(values, f): @@ -1111,7 +1159,9 @@ 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"): - return self.array.memory_usage(deep=deep) + # pandas\core\base.py:1379: error: "ExtensionArray" has no + # attribute "memory_usage" [attr-defined] + return self.array.memory_usage(deep=deep) # type: ignore[attr-defined] v = self.array.nbytes if deep and is_object_dtype(self) and not PYPY: @@ -1245,7 +1295,9 @@ def searchsorted(self, value, side="left", sorter=None) -> np.ndarray: def drop_duplicates(self, keep="first"): duplicated = self.duplicated(keep=keep) - result = self[np.logical_not(duplicated)] + # pandas\core\base.py:1507: error: Value of type "IndexOpsMixin" is not + # indexable [index] + result = self[np.logical_not(duplicated)] # type: ignore[index] return result def duplicated(self, keep="first"): diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index c971551a7f400..88a25ad9996a0 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -659,7 +659,11 @@ def visit_Call(self, node, side=None, **kwargs): raise if res is None: - raise ValueError(f"Invalid function call {node.func.id}") + # pandas\core\computation\expr.py:663: error: "expr" has no + # attribute "id" [attr-defined] + raise ValueError( + f"Invalid function call {node.func.id}" # type: ignore[attr-defined] + ) if hasattr(res, "value"): res = res.value @@ -680,7 +684,12 @@ def visit_Call(self, node, side=None, **kwargs): for key in node.keywords: if not isinstance(key, ast.keyword): - raise ValueError(f"keyword error in function call '{node.func.id}'") + # pandas\core\computation\expr.py:684: error: "expr" has no + # attribute "id" [attr-defined] + raise ValueError( + "keyword error in function call " # type: ignore[attr-defined] + f"'{node.func.id}'" + ) if key.arg: kwargs[key.arg] = self.visit(key.value).value diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py index 5759cd17476d6..74bee80c6c8a6 100644 --- a/pandas/core/computation/ops.py +++ b/pandas/core/computation/ops.py @@ -69,7 +69,9 @@ 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 - supr_new = super(Term, klass).__new__ + # pandas\core\computation\ops.py:72: error: Argument 2 for "super" not + # an instance of argument 1 [misc] + supr_new = super(Term, klass).__new__ # type: ignore[misc] return supr_new(klass) is_local: bool @@ -589,7 +591,8 @@ def __init__(self, func, args): self.func = func def __call__(self, env): - operands = [op(env) for op in self.operands] + # pandas\core\computation\ops.py:592: error: "Op" not callable [operator] + operands = [op(env) for op in self.operands] # type: ignore[operator] with np.errstate(all="ignore"): return self.func.func(*operands) diff --git a/pandas/core/computation/scope.py b/pandas/core/computation/scope.py index 7a9b8caa985e3..d2708da04b7e9 100644 --- a/pandas/core/computation/scope.py +++ b/pandas/core/computation/scope.py @@ -129,15 +129,29 @@ def __init__( # shallow copy here because we don't want to replace what's in # scope when we align terms (alignment accesses the underlying # numpy array of pandas objects) - self.scope = self.scope.new_child((global_dict or frame.f_globals).copy()) + + # pandas\core\computation\scope.py:132: error: Incompatible types + # in assignment (expression has type "ChainMap[str, Any]", variable + # has type "DeepChainMap[str, Any]") [assignment] + self.scope = self.scope.new_child( # type: ignore[assignment] + (global_dict or frame.f_globals).copy() + ) if not isinstance(local_dict, Scope): - self.scope = self.scope.new_child((local_dict or frame.f_locals).copy()) + # pandas\core\computation\scope.py:134: error: Incompatible + # types in assignment (expression has type "ChainMap[str, + # Any]", variable has type "DeepChainMap[str, Any]") + # [assignment] + self.scope = self.scope.new_child( # type: ignore[assignment] + (local_dict or frame.f_locals).copy() + ) finally: del frame # assumes that resolvers are going from outermost scope to inner if isinstance(local_dict, Scope): - resolvers += tuple(local_dict.resolvers.maps) + # pandas\core\computation\scope.py:140: error: Cannot determine + # type of 'resolvers' [has-type] + resolvers += tuple(local_dict.resolvers.maps) # type: ignore[has-type] self.resolvers = DeepChainMap(*resolvers) self.temps = {} @@ -224,7 +238,9 @@ def swapkey(self, old_key: str, new_key: str, new_value=None): for mapping in maps: if old_key in mapping: - mapping[new_key] = new_value + # pandas\core\computation\scope.py:228: error: Unsupported + # target for indexed assignment ("Mapping[Any, Any]") [index] + mapping[new_key] = new_value # type: ignore[index] return def _get_vars(self, stack, scopes: List[str]): @@ -243,7 +259,11 @@ def _get_vars(self, stack, scopes: List[str]): for scope, (frame, _, _, _, _, _) in variables: try: d = getattr(frame, "f_" + scope) - self.scope = self.scope.new_child(d) + # pandas\core\computation\scope.py:247: error: Incompatible + # types in assignment (expression has type "ChainMap[str, + # Any]", variable has type "DeepChainMap[str, Any]") + # [assignment] + self.scope = self.scope.new_child(d) # type: ignore[assignment] finally: # won't remove it, but DECREF it # in Py3 this probably isn't necessary since frame won't be @@ -310,5 +330,16 @@ def full_scope(self): vars : DeepChainMap All variables in this scope. """ - maps = [self.temps] + self.resolvers.maps + self.scope.maps + # 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] + maps = ( + [self.temps] + + self.resolvers.maps # type: ignore[operator] + + self.scope.maps # type: ignore[operator] + ) return DeepChainMap(*maps) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index bfb633ae55095..80743f8cc924b 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3859,7 +3859,12 @@ def reindexer(value): value, len(self.index), infer_dtype ) else: - value = cast_scalar_to_array(len(self.index), value) + # pandas\core\frame.py:3827: error: Argument 1 to + # "cast_scalar_to_array" has incompatible type "int"; expected + # "Tuple[Any, ...]" [arg-type] + value = cast_scalar_to_array( + len(self.index), value # type: ignore[arg-type] + ) value = maybe_cast_to_datetime(value, infer_dtype) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 02fa7308e7ee8..8470ef7ba5efb 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -10706,7 +10706,9 @@ def _add_numeric_operations(cls): def any(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): return NDFrame.any(self, axis, bool_only, skipna, level, **kwargs) - cls.any = any + # pandas\core\generic.py:10725: error: Cannot assign to a method + # [assignment] + cls.any = any # type: ignore[assignment] @doc( _bool_doc, @@ -10721,7 +10723,14 @@ def any(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): def all(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): return NDFrame.all(self, axis, bool_only, skipna, level, **kwargs) - cls.all = all + # pandas\core\generic.py:10719: error: Cannot assign to a method + # [assignment] + + # pandas\core\generic.py:10719: error: Incompatible types in assignment + # (expression has type "Callable[[Iterable[object]], bool]", variable + # has type "Callable[[NDFrame, Any, Any, Any, Any, KwArg(Any)], Any]") + # [assignment] + cls.all = all # type: ignore[assignment] @doc( desc="Return the mean absolute deviation of the values " @@ -10736,7 +10745,9 @@ def all(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): def mad(self, axis=None, skipna=None, level=None): return NDFrame.mad(self, axis, skipna, level) - cls.mad = mad + # pandas\core\generic.py:10736: error: Cannot assign to a method + # [assignment] + cls.mad = mad # type: ignore[assignment] @doc( _num_ddof_doc, @@ -10758,7 +10769,9 @@ def sem( ): return NDFrame.sem(self, axis, skipna, level, ddof, numeric_only, **kwargs) - cls.sem = sem + # pandas\core\generic.py:10758: error: Cannot assign to a method + # [assignment] + cls.sem = sem # type: ignore[assignment] @doc( _num_ddof_doc, @@ -10779,7 +10792,9 @@ def var( ): return NDFrame.var(self, axis, skipna, level, ddof, numeric_only, **kwargs) - cls.var = var + # pandas\core\generic.py:10779: error: Cannot assign to a method + # [assignment] + cls.var = var # type: ignore[assignment] @doc( _num_ddof_doc, @@ -10801,7 +10816,9 @@ def std( ): return NDFrame.std(self, axis, skipna, level, ddof, numeric_only, **kwargs) - cls.std = std + # pandas\core\generic.py:10801: error: Cannot assign to a method + # [assignment] + cls.std = std # type: ignore[assignment] @doc( _cnum_doc, @@ -10815,7 +10832,9 @@ def std( def cummin(self, axis=None, skipna=True, *args, **kwargs): return NDFrame.cummin(self, axis, skipna, *args, **kwargs) - cls.cummin = cummin + # pandas\core\generic.py:10815: error: Cannot assign to a method + # [assignment] + cls.cummin = cummin # type: ignore[assignment] @doc( _cnum_doc, @@ -10829,7 +10848,9 @@ def cummin(self, axis=None, skipna=True, *args, **kwargs): def cummax(self, axis=None, skipna=True, *args, **kwargs): return NDFrame.cummax(self, axis, skipna, *args, **kwargs) - cls.cummax = cummax + # pandas\core\generic.py:10829: error: Cannot assign to a method + # [assignment] + cls.cummax = cummax # type: ignore[assignment] @doc( _cnum_doc, @@ -10843,7 +10864,9 @@ def cummax(self, axis=None, skipna=True, *args, **kwargs): def cumsum(self, axis=None, skipna=True, *args, **kwargs): return NDFrame.cumsum(self, axis, skipna, *args, **kwargs) - cls.cumsum = cumsum + # pandas\core\generic.py:10843: error: Cannot assign to a method + # [assignment] + cls.cumsum = cumsum # type: ignore[assignment] @doc( _cnum_doc, @@ -10857,7 +10880,9 @@ def cumsum(self, axis=None, skipna=True, *args, **kwargs): def cumprod(self, axis=None, skipna=True, *args, **kwargs): return NDFrame.cumprod(self, axis, skipna, *args, **kwargs) - cls.cumprod = cumprod + # pandas\core\generic.py:10857: error: Cannot assign to a method + # [assignment] + cls.cumprod = cumprod # type: ignore[assignment] @doc( _num_doc, @@ -10883,7 +10908,9 @@ def sum( self, axis, skipna, level, numeric_only, min_count, **kwargs ) - cls.sum = sum + # pandas\core\generic.py:10883: error: Cannot assign to a method + # [assignment] + cls.sum = sum # type: ignore[assignment] @doc( _num_doc, @@ -10908,7 +10935,9 @@ def prod( self, axis, skipna, level, numeric_only, min_count, **kwargs ) - cls.prod = prod + # pandas\core\generic.py:10908: error: Cannot assign to a method + # [assignment] + cls.prod = prod # type: ignore[assignment] cls.product = prod @doc( @@ -10924,7 +10953,9 @@ def prod( def mean(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): return NDFrame.mean(self, axis, skipna, level, numeric_only, **kwargs) - cls.mean = mean + # pandas\core\generic.py:10924: error: Cannot assign to a method + # [assignment] + cls.mean = mean # type: ignore[assignment] @doc( _num_doc, @@ -10939,7 +10970,9 @@ def mean(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): def skew(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): return NDFrame.skew(self, axis, skipna, level, numeric_only, **kwargs) - cls.skew = skew + # pandas\core\generic.py:10939: error: Cannot assign to a method + # [assignment] + cls.skew = skew # type: ignore[assignment] @doc( _num_doc, @@ -10957,7 +10990,9 @@ def skew(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): def kurt(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): return NDFrame.kurt(self, axis, skipna, level, numeric_only, **kwargs) - cls.kurt = kurt + # pandas\core\generic.py:10957: error: Cannot assign to a method + # [assignment] + cls.kurt = kurt # type: ignore[assignment] cls.kurtosis = kurt @doc( @@ -10975,7 +11010,9 @@ def median( ): return NDFrame.median(self, axis, skipna, level, numeric_only, **kwargs) - cls.median = median + # pandas\core\generic.py:10975: error: Cannot assign to a method + # [assignment] + cls.median = median # type: ignore[assignment] @doc( _num_doc, @@ -10992,7 +11029,9 @@ def median( def max(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): return NDFrame.max(self, axis, skipna, level, numeric_only, **kwargs) - cls.max = max + # pandas\core\generic.py:10992: error: Cannot assign to a method + # [assignment] + cls.max = max # type: ignore[assignment] @doc( _num_doc, @@ -11009,7 +11048,9 @@ def max(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): def min(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): return NDFrame.min(self, axis, skipna, level, numeric_only, **kwargs) - cls.min = min + # pandas\core\generic.py:11009: error: Cannot assign to a method + # [assignment] + cls.min = min # type: ignore[assignment] @doc(Rolling) def rolling( @@ -11115,34 +11156,38 @@ def _inplace_method(self, other, op): return self def __iadd__(self, other): - return self._inplace_method(other, type(self).__add__) + return self._inplace_method(other, type(self).__add__) # type: ignore[operator] def __isub__(self, other): - return self._inplace_method(other, type(self).__sub__) + return self._inplace_method(other, type(self).__sub__) # type: ignore[operator] def __imul__(self, other): - return self._inplace_method(other, type(self).__mul__) + return self._inplace_method(other, type(self).__mul__) # type: ignore[operator] def __itruediv__(self, other): - return self._inplace_method(other, type(self).__truediv__) + return self._inplace_method( + other, type(self).__truediv__ # type: ignore[operator] + ) def __ifloordiv__(self, other): - return self._inplace_method(other, type(self).__floordiv__) + return self._inplace_method( + other, type(self).__floordiv__ # type: ignore[operator] + ) def __imod__(self, other): - return self._inplace_method(other, type(self).__mod__) + return self._inplace_method(other, type(self).__mod__) # type: ignore[operator] def __ipow__(self, other): - return self._inplace_method(other, type(self).__pow__) + return self._inplace_method(other, type(self).__pow__) # type: ignore[operator] def __iand__(self, other): - return self._inplace_method(other, type(self).__and__) + return self._inplace_method(other, type(self).__and__) # type: ignore[operator] def __ior__(self, other): - return self._inplace_method(other, type(self).__or__) + return self._inplace_method(other, type(self).__or__) # type: ignore[operator] def __ixor__(self, other): - return self._inplace_method(other, type(self).__xor__) + return self._inplace_method(other, type(self).__xor__) # type: ignore[operator] # ---------------------------------------------------------------------- # Misc methods diff --git a/pandas/core/groupby/base.py b/pandas/core/groupby/base.py index 8e278dc81a8cc..f205226c03a53 100644 --- a/pandas/core/groupby/base.py +++ b/pandas/core/groupby/base.py @@ -49,7 +49,9 @@ def _gotitem(self, key, ndim, subset=None): """ # create a new object to prevent aliasing if subset is None: - subset = self.obj + # pandas\core\groupby\base.py:52: error: "GotItemMixin" has no + # attribute "obj" [attr-defined] + subset = self.obj # type: ignore[attr-defined] # we need to make a shallow copy of ourselves # with the same groupby @@ -57,11 +59,25 @@ def _gotitem(self, key, ndim, subset=None): # Try to select from a DataFrame, falling back to a Series try: - groupby = self._groupby[key] + # pandas\core\groupby\base.py:60: error: "GotItemMixin" has no + # attribute "_groupby" [attr-defined] + groupby = self._groupby[key] # type: ignore[attr-defined] except IndexError: - groupby = self._groupby + # pandas\core\groupby\base.py:62: error: "GotItemMixin" has no + # attribute "_groupby" [attr-defined] + groupby = self._groupby # type: ignore[attr-defined] - self = type(self)(subset, groupby=groupby, parent=self, **kwargs) + # pandas\core\groupby\base.py:64: error: Too many arguments for + # "GotItemMixin" [call-arg] + + # pandas\core\groupby\base.py:64: error: Unexpected keyword argument + # "groupby" for "GotItemMixin" [call-arg] + + # pandas\core\groupby\base.py:64: error: Unexpected keyword argument + # "parent" for "GotItemMixin" [call-arg] + self = type(self)( + subset, groupby=groupby, parent=self, **kwargs # type: ignore[call-arg] + ) self._reset_cache() if subset.ndim == 2 and (is_scalar(key) and key in subset or is_list_like(key)): self._selection = key diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index ff5379567f090..e8af9da30a298 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -307,7 +307,10 @@ def _get_grouper(self, obj, validate: bool = True): a tuple of binner, grouper, obj (possibly sorted) """ self._set_grouper(obj) - self.grouper, _, self.obj = get_grouper( + # pandas\core\groupby\grouper.py:310: error: Value of type variable + # "FrameOrSeries" of "get_grouper" cannot be "Optional[Any]" + # [type-var] + self.grouper, _, self.obj = get_grouper( # type: ignore[type-var] self.obj, [self.key], axis=self.axis, @@ -345,7 +348,9 @@ def _set_grouper(self, obj: FrameOrSeries, sort: bool = False): if getattr(self.grouper, "name", None) == key and isinstance( obj, ABCSeries ): - ax = self._grouper.take(obj.index) + # pandas\core\groupby\grouper.py:348: error: Item "None" of + # "Optional[Any]" has no attribute "take" [union-attr] + ax = self._grouper.take(obj.index) # type: ignore[union-attr] else: if key not in obj._info_axis: raise KeyError(f"The grouper name {key} is not found") @@ -379,7 +384,9 @@ def _set_grouper(self, obj: FrameOrSeries, sort: bool = False): @property def groups(self): - return self.grouper.groups + # pandas\core\groupby\grouper.py:382: error: Item "None" of + # "Optional[Any]" has no attribute "groups" [union-attr] + return self.grouper.groups # type: ignore[union-attr] def __repr__(self) -> str: attrs_list = ( diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 1be979b1b899c..859c26a40e50d 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -324,7 +324,9 @@ def _format_attrs(self): "categories", ibase.default_pprint(self.categories, max_seq_items=max_categories), ), - ("ordered", self.ordered), + # pandas\core\indexes\category.py:315: error: "CategoricalIndex" + # has no attribute "ordered" [attr-defined] + ("ordered", self.ordered), # type: ignore[attr-defined] ] if self.name is not None: attrs.append(("name", ibase.default_pprint(self.name))) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 2cb66557b3bab..40a6086f69f85 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -745,7 +745,11 @@ def intersection(self, other, sort=False): start = right[0] if end < start: - result = type(self)(data=[], dtype=self.dtype, freq=self.freq) + # pandas\core\indexes\datetimelike.py:758: error: Unexpected + # keyword argument "freq" for "DatetimeTimedeltaMixin" [call-arg] + result = type(self)( + data=[], dtype=self.dtype, freq=self.freq # type: ignore[call-arg] + ) else: lslice = slice(*left.slice_locs(start, end)) left_chunk = left._values[lslice] @@ -874,7 +878,11 @@ def _union(self, other, sort): i8self = Int64Index._simple_new(self.asi8) i8other = Int64Index._simple_new(other.asi8) i8result = i8self._union(i8other, sort=sort) - result = type(self)(i8result, dtype=self.dtype, freq="infer") + # pandas\core\indexes\datetimelike.py:887: error: Unexpected + # keyword argument "freq" for "DatetimeTimedeltaMixin" [call-arg] + result = type(self)( + i8result, dtype=self.dtype, freq="infer" # type: ignore[call-arg] + ) return result # -------------------------------------------------------------------- diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index aa16dc9752565..2739806a0f338 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -811,7 +811,9 @@ def slice_indexer(self, start=None, end=None, step=None, kind=None): end_casted = self._maybe_cast_slice_bound(end, "right", kind) mask = (self <= end_casted) & mask - indexer = mask.nonzero()[0][::step] + # pandas\core\indexes\datetimes.py:764: error: "bool" has no + # attribute "nonzero" [attr-defined] + indexer = mask.nonzero()[0][::step] # type: ignore[attr-defined] if len(indexer) == len(self): return slice(None) else: diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index 921c7aac2c85b..3103c27b35d74 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -220,7 +220,9 @@ def __getitem__(self, key): if result.ndim == 1: return type(self)(result, name=self.name) # Unpack to ndarray for MPL compat - result = result._data + # pandas\core\indexes\extension.py:220: error: "ExtensionArray" has + # no attribute "_data" [attr-defined] + result = result._data # type: ignore[attr-defined] # Includes cases where we get a 2D ndarray back for MPL compat deprecate_ndim_indexing(result) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 65e71a6109a5a..5a3f2b0853c4f 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1449,7 +1449,9 @@ def _set_names(self, names, level=None, validate=True): raise TypeError( f"{type(self).__name__}.name must be a hashable type" ) - self._names[lev] = name + # pandas\core\indexes\multi.py:1448: error: Cannot determine type + # of '__setitem__' [has-type] + self._names[lev] = name # type: ignore[has-type] # If .levels has been accessed, the names in our cache will be stale. self._reset_cache() @@ -3506,8 +3508,13 @@ def intersection(self, other, sort=False): if uniq_tuples is None: other_uniq = set(rvals) seen = set() + # pandas\core\indexes\multi.py:3503: error: "add" of "set" does not + # return a value [func-returns-value] uniq_tuples = [ - x for x in lvals if x in other_uniq and not (x in seen or seen.add(x)) + x + for x in lvals + if x in other_uniq + and not (x in seen or seen.add(x)) # type: ignore[func-returns-value] ] if sort is None: diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 78d217c4688b6..fccedd75c4531 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -94,7 +94,10 @@ def __init__(self, obj, groupby=None, axis=0, kind=None, **kwargs): self.as_index = True self.exclusions = set() self.binner = None - self.grouper = None + # pandas\core\resample.py:96: error: Incompatible types in assignment + # (expression has type "None", variable has type "BaseGrouper") + # [assignment] + self.grouper = None # type: ignore[assignment] if self.groupby is not None: self.groupby._set_grouper(self._convert_obj(obj), sort=True) @@ -410,14 +413,21 @@ def _apply_loffset(self, result): result : Series or DataFrame the result of resample """ + # pandas\core\resample.py:409: error: Cannot determine type of + # 'loffset' [has-type] needs_offset = ( - isinstance(self.loffset, (DateOffset, timedelta, np.timedelta64)) + isinstance( + self.loffset, # type: ignore[has-type] + (DateOffset, timedelta, np.timedelta64), + ) and isinstance(result.index, DatetimeIndex) and len(result.index) > 0 ) if needs_offset: - result.index = result.index + self.loffset + # pandas\core\resample.py:415: error: Cannot determine type of + # 'loffset' [has-type] + result.index = result.index + self.loffset # type: ignore[has-type] self.loffset = None return result @@ -852,7 +862,9 @@ def std(self, ddof=1, *args, **kwargs): Standard deviation of values within each group. """ nv.validate_resampler_func("std", args, kwargs) - return self._downsample("std", ddof=ddof) + # pandas\core\resample.py:850: error: Unexpected keyword argument + # "ddof" for "_downsample" [call-arg] + return self._downsample("std", ddof=ddof) # type: ignore[call-arg] def var(self, ddof=1, *args, **kwargs): """ @@ -869,7 +881,9 @@ def var(self, ddof=1, *args, **kwargs): Variance of values within each group. """ nv.validate_resampler_func("var", args, kwargs) - return self._downsample("var", ddof=ddof) + # pandas\core\resample.py:867: error: Unexpected keyword argument + # "ddof" for "_downsample" [call-arg] + return self._downsample("var", ddof=ddof) # type: ignore[call-arg] @doc(GroupBy.size) def size(self): @@ -927,7 +941,12 @@ def quantile(self, q=0.5, **kwargs): Return a DataFrame, where the coulmns are groupby columns, and the values are its quantiles. """ - return self._downsample("quantile", q=q, **kwargs) + # pandas\core\resample.py:920: error: Unexpected keyword argument "q" + # for "_downsample" [call-arg] + + # pandas\core\resample.py:920: error: Too many arguments for + # "_downsample" [call-arg] + return self._downsample("quantile", q=q, **kwargs) # type: ignore[call-arg] # downsample methods @@ -979,7 +998,9 @@ def __init__(self, obj, *args, **kwargs): for attr in self._attributes: setattr(self, attr, kwargs.get(attr, getattr(parent, attr))) - super().__init__(None) + # pandas\core\resample.py:972: error: Too many arguments for "__init__" + # of "object" [call-arg] + super().__init__(None) # type: ignore[call-arg] self._groupby = groupby self._groupby.mutated = True self._groupby.grouper.mutated = True @@ -1044,7 +1065,12 @@ def _downsample(self, how, **kwargs): # do we have a regular frequency if ax.freq is not None or ax.inferred_freq is not None: - if len(self.grouper.binlabels) > len(ax) and how is None: + # pandas\core\resample.py:1037: error: "BaseGrouper" has no + # attribute "binlabels" [attr-defined] + if ( + len(self.grouper.binlabels) > len(ax) # type: ignore[attr-defined] + and how is None + ): # let's do an asfreq return self.asfreq() diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index aa883d518f8d1..d49e834fedb2d 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -965,7 +965,10 @@ def _get_merge_keys(self): """ left_keys = [] right_keys = [] - join_names = [] + # pandas\core\reshape\merge.py:966: error: Need type annotation for + # 'join_names' (hint: "join_names: List[] = ...") + # [var-annotated] + join_names = [] # type: ignore[var-annotated] right_drop = [] left_drop = [] diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 03c61c3ed8376..dd30bf37793d0 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -755,7 +755,10 @@ def __init__( self.mode = mode def __fspath__(self): - return stringify_path(self.path) + # pandas\io\excel\_base.py:744: error: Argument 1 to "stringify_path" + # has incompatible type "Optional[Any]"; expected "Union[str, Path, + # IO[Any], IOBase]" [arg-type] + return stringify_path(self.path) # type: ignore[arg-type] def _get_sheet_name(self, sheet_name): if sheet_name is None: diff --git a/pandas/io/formats/console.py b/pandas/io/formats/console.py index 50e69f7e8b435..ab9c9fe995008 100644 --- a/pandas/io/formats/console.py +++ b/pandas/io/formats/console.py @@ -69,7 +69,9 @@ def check_main(): return not hasattr(main, "__file__") or get_option("mode.sim_interactive") try: - return __IPYTHON__ or check_main() + # pandas\io\formats\console.py:72: error: Name '__IPYTHON__' is not + # defined [name-defined] + return __IPYTHON__ or check_main() # type: ignore[name-defined] except NameError: return check_main() @@ -83,7 +85,9 @@ def in_ipython_frontend(): bool """ try: - ip = get_ipython() + # pandas\io\formats\console.py:86: error: Name 'get_ipython' is not + # defined [name-defined] + ip = get_ipython() # type: ignore[name-defined] return "zmq" in str(type(ip)).lower() except NameError: pass diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index 5013365896fb2..9793f7a1e4613 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -590,10 +590,17 @@ def _format_header_regular(self): colnames = self.columns if has_aliases: - if len(self.header) != len(self.columns): + # pandas\io\formats\excel.py:593: error: Argument 1 to "len" + # has incompatible type "Union[Sequence[Optional[Hashable]], + # bool]"; expected "Sized" [arg-type] + if len(self.header) != len(self.columns): # type: ignore[arg-type] + # pandas\io\formats\excel.py:595: error: Argument 1 to + # "len" has incompatible type + # "Union[Sequence[Optional[Hashable]], bool]"; expected + # "Sized" [arg-type] raise ValueError( - f"Writing {len(self.columns)} cols but got {len(self.header)} " - "aliases" + f"Writing {len(self.columns)} " # type: ignore[arg-type] + f"cols but got {len(self.header)} aliases" ) else: colnames = self.header @@ -615,7 +622,10 @@ def _format_header(self): "" ] * len(self.columns) if reduce(lambda x, y: x and y, map(lambda x: x != "", row)): - gen2 = ( + # pandas\io\formats\excel.py:618: error: Incompatible types in + # assignment (expression has type "Generator[ExcelCell, None, + # None]", variable has type "Tuple[]") [assignment] + gen2 = ( # type: ignore[assignment] ExcelCell(self.rowcounter, colindex, val, self.header_style) for colindex, val in enumerate(row) ) @@ -805,7 +815,12 @@ def write( if isinstance(writer, ExcelWriter): need_save = False else: - writer = ExcelWriter(stringify_path(writer), engine=engine) + # pandas\io\formats\excel.py:808: error: Cannot instantiate + # abstract class 'ExcelWriter' with abstract attributes 'engine', + # 'save', 'supported_extensions' and 'write_cells' [abstract] + writer = ExcelWriter( # type: ignore[abstract] + stringify_path(writer), engine=engine + ) need_save = True formatted_cells = self.get_formatted_cells() diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 43e76d0aef490..5b69ef4eba26e 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1342,7 +1342,16 @@ def _value_formatter( def base_formatter(v): assert float_format is not None # for mypy - return float_format(value=v) if notna(v) else self.na_rep + # pandas\io\formats\format.py:1411: error: "str" not callable + # [operator] + + # pandas\io\formats\format.py:1411: error: Unexpected keyword + # argument "value" for "__call__" of "EngFormatter" [call-arg] + return ( + float_format(value=v) # type: ignore[operator,call-arg] + if notna(v) + else self.na_rep + ) else: diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index e4895d280c241..5725e2304e1d2 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -851,7 +851,10 @@ def _get_options_with_defaults(self, engine): options[argname] = value if engine == "python-fwf": - for argname, default in _fwf_defaults.items(): + # pandas\io\parsers.py:907: error: Incompatible types in assignment + # (expression has type "object", variable has type "Union[int, str, + # None]") [assignment] + for argname, default in _fwf_defaults.items(): # type: ignore[assignment] options[argname] = kwds.get(argname, default) return options @@ -1035,9 +1038,18 @@ def __next__(self): def _make_engine(self, engine="c"): mapping = { - "c": CParserWrapper, - "python": PythonParser, - "python-fwf": FixedWidthFieldParser, + # pandas\io\parsers.py:1099: error: Dict entry 0 has incompatible + # type "str": "Type[CParserWrapper]"; expected "str": + # "Type[ParserBase]" [dict-item] + "c": CParserWrapper, # type: ignore[dict-item] + # pandas\io\parsers.py:1100: error: Dict entry 1 has incompatible + # type "str": "Type[PythonParser]"; expected "str": + # "Type[ParserBase]" [dict-item] + "python": PythonParser, # type: ignore[dict-item] + # pandas\io\parsers.py:1101: error: Dict entry 2 has incompatible + # type "str": "Type[FixedWidthFieldParser]"; expected "str": + # "Type[ParserBase]" [dict-item] + "python-fwf": FixedWidthFieldParser, # type: ignore[dict-item] } try: klass = mapping[engine] @@ -1394,7 +1406,9 @@ def _validate_parse_dates_presence(self, columns: List[str]) -> None: ) def close(self): - self.handles.close() + # pandas\io\parsers.py:1409: error: "ParserBase" has no attribute + # "handles" [attr-defined] + self.handles.close() # type: ignore[attr-defined] @property def _has_complex_date_col(self): @@ -1490,7 +1504,9 @@ def _maybe_dedup_names(self, names): # would be nice! if self.mangle_dupe_cols: names = list(names) # so we can index - counts = defaultdict(int) + # pandas\io\parsers.py:1559: error: Need type annotation for + # 'counts' [var-annotated] + counts = defaultdict(int) # type: ignore[var-annotated] is_potential_mi = _is_potential_multi_index(names, self.index_col) for i, col in enumerate(names): @@ -1535,7 +1551,9 @@ def _make_index(self, data, alldata, columns, indexnamerow=False): # add names for the index if indexnamerow: coffset = len(indexnamerow) - len(columns) - index = index.set_names(indexnamerow[:coffset]) + # pandas\io\parsers.py:1604: error: Item "None" of "Optional[Any]" + # has no attribute "set_names" [union-attr] + index = index.set_names(indexnamerow[:coffset]) # type: ignore[union-attr] # maybe create a mi on the columns columns = self._maybe_make_multi_index_columns(columns, self.col_names) @@ -1609,7 +1627,9 @@ def _agg_index(self, index, try_parse_dates=True) -> Index: col_na_fvalues = set() if isinstance(self.na_values, dict): - col_name = self.index_names[i] + # pandas\io\parsers.py:1678: error: Value of type + # "Optional[Any]" is not indexable [index] + col_name = self.index_names[i] # type: ignore[index] if col_name is not None: col_na_values, col_na_fvalues = _get_na_values( col_name, self.na_values, self.na_fvalues, self.keep_default_na @@ -1840,7 +1860,30 @@ def __init__(self, src, **kwds): kwds.pop("memory_map", None) kwds.pop("compression", None) if self.handles.is_mmap and hasattr(self.handles.handle, "mmap"): - self.handles.handle = self.handles.handle.mmap + # pandas\io\parsers.py:1861: error: Item "IO[Any]" of + # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase, + # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr] + + # pandas\io\parsers.py:1861: error: Item "RawIOBase" of + # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase, + # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr] + + # pandas\io\parsers.py:1861: error: Item "BufferedIOBase" of + # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase, + # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr] + + # pandas\io\parsers.py:1861: error: Item "TextIOBase" of + # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase, + # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr] + + # pandas\io\parsers.py:1861: error: Item "TextIOWrapper" of + # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase, + # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr] + + # pandas\io\parsers.py:1861: error: Item "mmap" of "Union[IO[Any], + # RawIOBase, BufferedIOBase, TextIOBase, TextIOWrapper, mmap]" has + # no attribute "mmap" [union-attr] + self.handles.handle = self.handles.handle.mmap # type: ignore[union-attr] # #2442 kwds["allow_leading_cols"] = self.index_col is not False @@ -1924,7 +1967,12 @@ def __init__(self, src, **kwds): self.index_names = index_names if self._reader.header is None and not passed_names: - self.index_names = [None] * len(self.index_names) + # pandas\io\parsers.py:1997: error: Argument 1 to "len" has + # incompatible type "Optional[Any]"; expected "Sized" + # [arg-type] + self.index_names = [None] * len( + self.index_names # type: ignore[arg-type] + ) self._implicit_index = self._reader.leading_cols > 0 @@ -1956,14 +2004,20 @@ def _set_noconvert_columns(self): usecols = self.names[:] else: # Usecols is empty. - usecols = None + + # pandas\io\parsers.py:2030: error: Incompatible types in + # assignment (expression has type "None", variable has type + # "List[Any]") [assignment] + usecols = None # type: ignore[assignment] def _set(x): if usecols is not None and is_integer(x): x = usecols[x] if not is_integer(x): - x = names.index(x) + # pandas\io\parsers.py:2037: error: Item "None" of + # "Optional[Any]" has no attribute "index" [union-attr] + x = names.index(x) # type: ignore[union-attr] self._reader.set_noconvert(x) @@ -2057,7 +2111,11 @@ def read(self, nrows=None): data = sorted(data.items()) # ugh, mutation - names = list(self.orig_names) + + # pandas\io\parsers.py:2131: error: Argument 1 to "list" has + # incompatible type "Optional[Any]"; expected "Iterable[Any]" + # [arg-type] + names = list(self.orig_names) # type: ignore[arg-type] names = self._maybe_dedup_names(names) if self.usecols is not None: @@ -2391,7 +2449,11 @@ def _read(): reader = _read() - self.data = reader + # pandas\io\parsers.py:2427: error: Incompatible types in assignment + # (expression has type "_reader", variable has type "Union[IO[Any], + # RawIOBase, BufferedIOBase, TextIOBase, TextIOWrapper, mmap, None]") + # [assignment] + self.data = reader # type: ignore[assignment] def read(self, rows=None): try: @@ -2405,7 +2467,10 @@ def read(self, rows=None): # done with first read, next time raise StopIteration self._first_chunk = False - columns = list(self.orig_names) + # pandas\io\parsers.py:2480: error: Argument 1 to "list" has + # incompatible type "Optional[Any]"; expected "Iterable[Any]" + # [arg-type] + columns = list(self.orig_names) # type: ignore[arg-type] if not len(content): # pragma: no cover # DataFrame with the right metadata, even though it's length 0 names = self._maybe_dedup_names(self.orig_names) @@ -2453,7 +2518,9 @@ def _exclude_implicit_index(self, alldata): # legacy def get_chunk(self, size=None): if size is None: - size = self.chunksize + # pandas\io\parsers.py:2528: error: "PythonParser" has no attribute + # "chunksize" [attr-defined] + size = self.chunksize # type: ignore[attr-defined] return self.read(rows=size) def _convert_data(self, data): @@ -2462,8 +2529,15 @@ def _clean_mapping(mapping): """converts col numbers to names""" clean = {} for col, v in mapping.items(): - if isinstance(col, int) and col not in self.orig_names: - col = self.orig_names[col] + # pandas\io\parsers.py:2537: error: Unsupported right operand + # type for in ("Optional[Any]") [operator] + if ( + isinstance(col, int) + and col not in self.orig_names # type: ignore[operator] + ): + # pandas\io\parsers.py:2538: error: Value of type + # "Optional[Any]" is not indexable [index] + col = self.orig_names[col] # type: ignore[index] clean[col] = v return clean @@ -2483,8 +2557,15 @@ def _clean_mapping(mapping): na_value = self.na_values[col] na_fvalue = self.na_fvalues[col] - if isinstance(col, int) and col not in self.orig_names: - col = self.orig_names[col] + # pandas\io\parsers.py:2558: error: Unsupported right operand + # type for in ("Optional[Any]") [operator] + if ( + isinstance(col, int) + and col not in self.orig_names # type: ignore[operator] + ): + # pandas\io\parsers.py:2559: error: Value of type + # "Optional[Any]" is not indexable [index] + col = self.orig_names[col] # type: ignore[index] clean_na_values[col] = na_value clean_na_fvalues[col] = na_fvalue @@ -2505,7 +2586,10 @@ def _infer_columns(self): names = self.names num_original_columns = 0 clear_buffer = True - unnamed_cols = set() + # pandas\io\parsers.py:2580: error: Need type annotation for + # 'unnamed_cols' (hint: "unnamed_cols: Set[] = ...") + # [var-annotated] + unnamed_cols = set() # type: ignore[var-annotated] if self.header is not None: header = self.header @@ -2519,7 +2603,9 @@ def _infer_columns(self): have_mi_columns = False header = [header] - columns = [] + # pandas\io\parsers.py:2594: error: Need type annotation for + # 'columns' (hint: "columns: List[] = ...") [var-annotated] + columns = [] # type: ignore[var-annotated] for level, hr in enumerate(header): try: line = self._buffered_line() @@ -2564,7 +2650,9 @@ def _infer_columns(self): this_columns.append(c) if not have_mi_columns and self.mangle_dupe_cols: - counts = defaultdict(int) + # pandas\io\parsers.py:2639: error: Need type annotation + # for 'counts' [var-annotated] + counts = defaultdict(int) # type: ignore[var-annotated] for i, col in enumerate(this_columns): cur_count = counts[col] @@ -2588,10 +2676,16 @@ def _infer_columns(self): if lc != unnamed_count and lc - ic > unnamed_count: clear_buffer = False - this_columns = [None] * lc + # pandas\io\parsers.py:2663: error: List item 0 has + # incompatible type "None"; expected "str" + # [list-item] + this_columns = [None] * lc # type: ignore[list-item] self.buf = [self.buf[-1]] - columns.append(this_columns) + # pandas\io\parsers.py:2666: error: Argument 1 to "append" of + # "list" has incompatible type "List[str]"; expected + # "List[None]" [arg-type] + columns.append(this_columns) # type: ignore[arg-type] unnamed_cols.update({this_columns[i] for i in this_unnamed_cols}) if len(columns) == 1: @@ -2636,9 +2730,19 @@ def _infer_columns(self): if not names: if self.prefix: - columns = [[f"{self.prefix}{i}" for i in range(ncols)]] + # pandas\io\parsers.py:2711: error: List comprehension has + # incompatible type List[str]; expected List[None] [misc] + columns = [ + [ + f"{self.prefix}{i}" # type: ignore[misc] + for i in range(ncols) + ] + ] else: - columns = [list(range(ncols))] + # pandas\io\parsers.py:2713: error: Argument 1 to "list" + # has incompatible type "range"; expected "Iterable[None]" + # [arg-type] + columns = [list(range(ncols))] # type: ignore[arg-type] columns = self._handle_usecols(columns, columns[0]) else: if self.usecols is None or len(names) >= num_original_columns: @@ -2790,7 +2894,10 @@ def _next_line(self): else: while self.skipfunc(self.pos): self.pos += 1 - next(self.data) + # pandas\io\parsers.py:2865: error: Argument 1 to "next" has + # incompatible type "Optional[Any]"; expected "Iterator[Any]" + # [arg-type] + next(self.data) # type: ignore[arg-type] while True: orig_line = self._next_iter_line(row_num=self.pos + 1) @@ -2851,7 +2958,10 @@ def _next_iter_line(self, row_num): row_num : The row number of the line being parsed. """ try: - return next(self.data) + # pandas\io\parsers.py:2926: error: Argument 1 to "next" has + # incompatible type "Optional[Any]"; expected "Iterator[Any]" + # [arg-type] + return next(self.data) # type: ignore[arg-type] except csv.Error as e: if self.warn_bad_lines or self.error_bad_lines: msg = str(e) @@ -3084,12 +3194,19 @@ def _rows_to_cols(self, content): for i, a in enumerate(zipped_content) if ( i < len(self.index_col) - or i - len(self.index_col) in self._col_indices + # pandas\io\parsers.py:3159: error: Unsupported right + # operand type for in ("Optional[Any]") [operator] + or i - len(self.index_col) # type: ignore[operator] + in self._col_indices ) ] else: zipped_content = [ - a for i, a in enumerate(zipped_content) if i in self._col_indices + # pandas\io\parsers.py:3164: error: Unsupported right + # operand type for in ("Optional[Any]") [operator] + a + for i, a in enumerate(zipped_content) + if i in self._col_indices # type: ignore[operator] ] return zipped_content @@ -3134,7 +3251,10 @@ def _get_lines(self, rows=None): try: if rows is not None: for _ in range(rows): - new_rows.append(next(self.data)) + # pandas\io\parsers.py:3209: error: Argument 1 to + # "next" has incompatible type "Optional[Any]"; + # expected "Iterator[Any]" [arg-type] + new_rows.append(next(self.data)) # type: ignore[arg-type] lines.extend(new_rows) else: rows = 0 @@ -3312,7 +3432,9 @@ def _clean_na_values(na_values, keep_default_na=True): na_values = STR_NA_VALUES else: na_values = set() - na_fvalues = set() + # pandas\io\parsers.py:3387: error: Need type annotation for + # 'na_fvalues' (hint: "na_fvalues: Set[] = ...") [var-annotated] + na_fvalues = set() # type: ignore[var-annotated] elif isinstance(na_values, dict): old_na_values = na_values.copy() na_values = {} # Prevent aliasing. @@ -3329,7 +3451,12 @@ def _clean_na_values(na_values, keep_default_na=True): v = set(v) | STR_NA_VALUES na_values[k] = v - na_fvalues = {k: _floatify_na_values(v) for k, v in na_values.items()} + # pandas\io\parsers.py:3404: error: Incompatible types in assignment + # (expression has type "Dict[Any, Any]", variable has type "Set[Any]") + # [assignment] + na_fvalues = { # type: ignore[assignment] + k: _floatify_na_values(v) for k, v in na_values.items() + } else: if not is_list_like(na_values): na_values = [na_values] @@ -3370,7 +3497,10 @@ def _clean_index_names(columns, index_col, unnamed_cols): # Only clean index names that were placeholders. for i, name in enumerate(index_names): if isinstance(name, str) and name in unnamed_cols: - index_names[i] = None + # pandas\io\parsers.py:3445: error: No overload variant of + # "__setitem__" of "list" matches argument types "int", "None" + # [call-overload] + index_names[i] = None # type: ignore[call-overload] return index_names, columns, index_col @@ -3447,11 +3577,15 @@ def _stringify_na_values(na_values): result.append(f"{v}.0") result.append(str(v)) - result.append(v) + # pandas\io\parsers.py:3522: error: Argument 1 to "append" of + # "list" has incompatible type "float"; expected "str" [arg-type] + result.append(v) # type: ignore[arg-type] except (TypeError, ValueError, OverflowError): pass try: - result.append(int(x)) + # pandas\io\parsers.py:3526: error: Argument 1 to "append" of + # "list" has incompatible type "int"; expected "str" [arg-type] + result.append(int(x)) # type: ignore[arg-type] except (TypeError, ValueError, OverflowError): pass return set(result) @@ -3622,7 +3756,11 @@ def __init__(self, f, **kwds): PythonParser.__init__(self, f, **kwds) def _make_reader(self, f): - self.data = FixedWidthReader( + # pandas\io\parsers.py:3730: error: Incompatible types in assignment + # (expression has type "FixedWidthReader", variable has type + # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase, TextIOWrapper, + # mmap, None]") [assignment] + self.data = FixedWidthReader( # type: ignore[assignment] f, self.colspecs, self.delimiter, diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 6c9924e0ada79..2501d84de4459 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -577,8 +577,20 @@ def _make_legend(self): if self.legend: if self.legend == "reverse": - self.legend_handles = reversed(self.legend_handles) - self.legend_labels = reversed(self.legend_labels) + # pandas\plotting\_matplotlib\core.py:578: error: + # Incompatible types in assignment (expression has type + # "Iterator[Any]", variable has type "List[Any]") + # [assignment] + self.legend_handles = reversed( # type: ignore[assignment] + self.legend_handles + ) + # pandas\plotting\_matplotlib\core.py:579: error: + # Incompatible types in assignment (expression has type + # "Iterator[Optional[Hashable]]", variable has type + # "List[Optional[Hashable]]") [assignment] + self.legend_labels = reversed( # type: ignore[assignment] + self.legend_labels + ) handles += self.legend_handles labels += self.legend_labels @@ -1101,7 +1113,11 @@ def _make_plot(self): it = self._iter_data(data=data, keep_index=True) else: x = self._get_xticks(convert_period=True) - plotf = self._plot + # pandas\plotting\_matplotlib\core.py:1100: error: Incompatible + # types in assignment (expression has type "Callable[[Any, Any, + # Any, Any, Any, Any, KwArg(Any)], Any]", variable has type + # "Callable[[Any, Any, Any, Any, KwArg(Any)], Any]") [assignment] + plotf = self._plot # type: ignore[assignment] it = self._iter_data() stacking_id = self._get_stacking_id() @@ -1547,7 +1563,10 @@ def blank_labeler(label, value): if labels is not None: blabels = [blank_labeler(l, value) for l, value in zip(labels, y)] else: - blabels = None + # pandas\plotting\_matplotlib\core.py:1546: error: Incompatible + # types in assignment (expression has type "None", variable has + # type "List[Any]") [assignment] + blabels = None # type: ignore[assignment] results = ax.pie(y, labels=blabels, **kwds) if kwds.get("autopct", None) is not None: diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py index 6e473bf5b182c..58f44104b99d6 100644 --- a/pandas/plotting/_misc.py +++ b/pandas/plotting/_misc.py @@ -530,7 +530,9 @@ def reset(self): ------- None """ - self.__init__() + # pandas\plotting\_misc.py:533: error: Cannot access "__init__" + # directly [misc] + self.__init__() # type: ignore[misc] def _get_canonical_key(self, key): return self._ALIASES.get(key, key) diff --git a/setup.cfg b/setup.cfg index b1f423c12ebf4..c83a83d599f6c 100644 --- a/setup.cfg +++ b/setup.cfg @@ -114,10 +114,11 @@ skip_glob = env, skip = pandas/__init__.py [mypy] -ignore_missing_imports=True -no_implicit_optional=True -check_untyped_defs=True -strict_equality=True +platform = linux-64 +ignore_missing_imports = True +no_implicit_optional = True +check_untyped_defs = True +strict_equality = True warn_redundant_casts = True warn_unused_ignores = True show_error_codes = True @@ -125,86 +126,8 @@ show_error_codes = True [mypy-pandas.tests.*] check_untyped_defs=False -[mypy-pandas._testing] -check_untyped_defs=False - [mypy-pandas._version] check_untyped_defs=False -[mypy-pandas.core.apply] -check_untyped_defs=False - -[mypy-pandas.core.arrays.datetimelike] -check_untyped_defs=False - -[mypy-pandas.core.arrays.string_] -check_untyped_defs=False - -[mypy-pandas.core.base] -check_untyped_defs=False - -[mypy-pandas.core.computation.expr] -check_untyped_defs=False - -[mypy-pandas.core.computation.ops] -check_untyped_defs=False - -[mypy-pandas.core.computation.scope] -check_untyped_defs=False - -[mypy-pandas.core.frame] -check_untyped_defs=False - -[mypy-pandas.core.generic] -check_untyped_defs=False - -[mypy-pandas.core.groupby.base] -check_untyped_defs=False - -[mypy-pandas.core.groupby.grouper] -check_untyped_defs=False - -[mypy-pandas.core.indexes.category] -check_untyped_defs=False - -[mypy-pandas.core.indexes.datetimelike] -check_untyped_defs=False - -[mypy-pandas.core.indexes.datetimes] -check_untyped_defs=False - -[mypy-pandas.core.indexes.extension] -check_untyped_defs=False - -[mypy-pandas.core.indexes.multi] -check_untyped_defs=False - -[mypy-pandas.core.resample] -check_untyped_defs=False - -[mypy-pandas.core.reshape.merge] -check_untyped_defs=False - [mypy-pandas.io.clipboard] check_untyped_defs=False - -[mypy-pandas.io.excel._base] -check_untyped_defs=False - -[mypy-pandas.io.formats.console] -check_untyped_defs=False - -[mypy-pandas.io.formats.excel] -check_untyped_defs=False - -[mypy-pandas.io.formats.format] -check_untyped_defs=False - -[mypy-pandas.io.parsers] -check_untyped_defs=False - -[mypy-pandas.plotting._matplotlib.core] -check_untyped_defs=False - -[mypy-pandas.plotting._misc] -check_untyped_defs=False