diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7c9ebf7d94173..1cb7b288aba69 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -74,7 +74,7 @@ repos: hooks: - id: isort - repo: https://github.com/asottile/pyupgrade - rev: v3.16.0 + rev: v3.17.0 hooks: - id: pyupgrade args: [--py310-plus] @@ -112,7 +112,7 @@ repos: types: [python] stages: [manual] additional_dependencies: &pyright_dependencies - - pyright@1.1.352 + - pyright@1.1.383 - id: pyright # note: assumes python env is setup and activated name: pyright reportGeneralTypeIssues diff --git a/environment.yml b/environment.yml index 34bc0591ca8df..ab834735441f0 100644 --- a/environment.yml +++ b/environment.yml @@ -76,10 +76,10 @@ dependencies: - cxx-compiler # code checks - - flake8=6.1.0 # run in subprocess over docstring examples - - mypy=1.9.0 # pre-commit uses locally installed mypy + - flake8=7.1.0 # run in subprocess over docstring examples + - mypy=1.11.2 # pre-commit uses locally installed mypy - tokenize-rt # scripts/check_for_inconsistent_pandas_namespace.py - - pre-commit>=3.6.0 + - pre-commit>=4.0.1 # documentation - gitpython # obtain contributors from git for whatsnew diff --git a/pandas/_config/config.py b/pandas/_config/config.py index 4ed2d4c3be692..25760df6bd7a4 100644 --- a/pandas/_config/config.py +++ b/pandas/_config/config.py @@ -411,7 +411,7 @@ def __dir__(self) -> list[str]: @contextmanager -def option_context(*args) -> Generator[None, None, None]: +def option_context(*args) -> Generator[None]: """ Context manager to temporarily set options in a ``with`` statement. @@ -718,7 +718,7 @@ def _build_option_description(k: str) -> str: @contextmanager -def config_prefix(prefix: str) -> Generator[None, None, None]: +def config_prefix(prefix: str) -> Generator[None]: """ contextmanager for multiple invocations of API with a common prefix diff --git a/pandas/_config/localization.py b/pandas/_config/localization.py index 61d88c43f0e4a..6602633f20399 100644 --- a/pandas/_config/localization.py +++ b/pandas/_config/localization.py @@ -25,7 +25,7 @@ @contextmanager def set_locale( new_locale: str | tuple[str, str], lc_var: int = locale.LC_ALL -) -> Generator[str | tuple[str, str], None, None]: +) -> Generator[str | tuple[str, str]]: """ Context manager for temporarily setting a locale. diff --git a/pandas/_testing/_warnings.py b/pandas/_testing/_warnings.py index cd2e2b4141ffd..a752c8db90f38 100644 --- a/pandas/_testing/_warnings.py +++ b/pandas/_testing/_warnings.py @@ -35,7 +35,7 @@ def assert_produces_warning( raise_on_extra_warnings: bool = True, match: str | tuple[str | None, ...] | None = None, must_find_all_warnings: bool = True, -) -> Generator[list[warnings.WarningMessage], None, None]: +) -> Generator[list[warnings.WarningMessage]]: """ Context manager for running code expected to either raise a specific warning, multiple specific warnings, or not raise any warnings. Verifies that the code diff --git a/pandas/_testing/contexts.py b/pandas/_testing/contexts.py index 4ca67d6fc082d..99826de51e1bf 100644 --- a/pandas/_testing/contexts.py +++ b/pandas/_testing/contexts.py @@ -29,7 +29,7 @@ @contextmanager def decompress_file( path: FilePath | BaseBuffer, compression: CompressionOptions -) -> Generator[IO[bytes], None, None]: +) -> Generator[IO[bytes]]: """ Open a compressed file and return a file object. @@ -50,7 +50,7 @@ def decompress_file( @contextmanager -def set_timezone(tz: str) -> Generator[None, None, None]: +def set_timezone(tz: str) -> Generator[None]: """ Context manager for temporarily setting a timezone. @@ -92,7 +92,7 @@ def setTZ(tz) -> None: @contextmanager -def ensure_clean(filename=None) -> Generator[Any, None, None]: +def ensure_clean(filename=None) -> Generator[Any]: """ Gets a temporary path and agrees to remove on close. @@ -124,7 +124,7 @@ def ensure_clean(filename=None) -> Generator[Any, None, None]: @contextmanager -def with_csv_dialect(name: str, **kwargs) -> Generator[None, None, None]: +def with_csv_dialect(name: str, **kwargs) -> Generator[None]: """ Context manager to temporarily register a CSV dialect for parsing CSV. diff --git a/pandas/compat/pickle_compat.py b/pandas/compat/pickle_compat.py index 28985a1380bee..beaaa3f8ed3cc 100644 --- a/pandas/compat/pickle_compat.py +++ b/pandas/compat/pickle_compat.py @@ -131,7 +131,7 @@ def loads( @contextlib.contextmanager -def patch_pickle() -> Generator[None, None, None]: +def patch_pickle() -> Generator[None]: """ Temporarily patch pickle to use our unpickler. """ diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 1f13459724d78..af2d6243ce4ed 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -246,12 +246,8 @@ def transform(self) -> DataFrame | Series: and not obj.empty ): raise ValueError("Transform function failed") - # error: Argument 1 to "__get__" of "AxisProperty" has incompatible type - # "Union[Series, DataFrame, GroupBy[Any], SeriesGroupBy, - # DataFrameGroupBy, BaseWindow, Resampler]"; expected "Union[DataFrame, - # Series]" if not isinstance(result, (ABCSeries, ABCDataFrame)) or not result.index.equals( - obj.index # type: ignore[arg-type] + obj.index ): raise ValueError("Function did not transform") @@ -803,7 +799,7 @@ def result_columns(self) -> Index: @property @abc.abstractmethod - def series_generator(self) -> Generator[Series, None, None]: + def series_generator(self) -> Generator[Series]: pass @staticmethod @@ -1128,7 +1124,7 @@ class FrameRowApply(FrameApply): axis: AxisInt = 0 @property - def series_generator(self) -> Generator[Series, None, None]: + def series_generator(self) -> Generator[Series]: return (self.obj._ixs(i, axis=1) for i in range(len(self.columns))) @staticmethod @@ -1235,7 +1231,7 @@ def apply_broadcast(self, target: DataFrame) -> DataFrame: return result.T @property - def series_generator(self) -> Generator[Series, None, None]: + def series_generator(self) -> Generator[Series]: values = self.values values = ensure_wrapped_if_datetimelike(values) assert len(values) > 0 diff --git a/pandas/core/arraylike.py b/pandas/core/arraylike.py index f70bb0743aa0f..43ac69508d1a4 100644 --- a/pandas/core/arraylike.py +++ b/pandas/core/arraylike.py @@ -403,12 +403,12 @@ def _reconstruct(result): # for np.(..) calls # kwargs cannot necessarily be handled block-by-block, so only # take this path if there are no kwargs - mgr = inputs[0]._mgr + mgr = inputs[0]._mgr # pyright: ignore[reportGeneralTypeIssues] result = mgr.apply(getattr(ufunc, method)) else: # otherwise specific ufunc methods (eg np..accumulate(..)) # Those can have an axis keyword and thus can't be called block-by-block - result = default_array_ufunc(inputs[0], ufunc, method, *inputs, **kwargs) + result = default_array_ufunc(inputs[0], ufunc, method, *inputs, **kwargs) # pyright: ignore[reportGeneralTypeIssues] # e.g. np.negative (only one reached), with "where" and "out" in kwargs result = reconstruct(result) diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index 00d46ab9296d0..c6fb5225d58f9 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -2426,7 +2426,7 @@ def _str_rindex(self, sub: str, start: int = 0, end: int | None = None) -> Self: result = self._apply_elementwise(predicate) return type(self)(pa.chunked_array(result)) - def _str_normalize(self, form: str) -> Self: + def _str_normalize(self, form: Literal["NFC", "NFD", "NFKC", "NFKD"]) -> Self: predicate = lambda val: unicodedata.normalize(form, val) result = self._apply_elementwise(predicate) return type(self)(pa.chunked_array(result)) diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py index 53ebc35b68d14..87c18fe346c62 100644 --- a/pandas/core/arrays/boolean.py +++ b/pandas/core/arrays/boolean.py @@ -369,7 +369,7 @@ def _coerce_to_array( assert dtype == "boolean" return coerce_to_array(value, copy=copy) - def _logical_method(self, other, op): + def _logical_method(self, other, op): # type: ignore[override] assert op.__name__ in {"or_", "ror_", "and_", "rand_", "xor", "rxor"} other_is_scalar = lib.is_scalar(other) mask = None diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 41128e52e31b3..43cc492f82885 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -2918,7 +2918,7 @@ def _generate_range( offset: BaseOffset, *, unit: str, -) -> Generator[Timestamp, None, None]: +) -> Generator[Timestamp]: """ Generates a sequence of dates corresponding to the specified time offset. Similar to dateutil.rrule except uses pandas DateOffset diff --git a/pandas/core/common.py b/pandas/core/common.py index ec0473a20458b..9788ec972ba1b 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -560,9 +560,7 @@ def convert_to_list_like( @contextlib.contextmanager -def temp_setattr( - obj, attr: str, value, condition: bool = True -) -> Generator[None, None, None]: +def temp_setattr(obj, attr: str, value, condition: bool = True) -> Generator[None]: """ Temporarily set attribute on an object. diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index f45bc453d2541..7025d8a72e561 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -168,7 +168,7 @@ def _preparse( the ``tokenize`` module and ``tokval`` is a string. """ assert callable(f), "f must be callable" - return tokenize.untokenize(f(x) for x in tokenize_string(source)) + return tokenize.untokenize(f(x) for x in tokenize_string(source)) # pyright: ignore[reportArgumentType] def _is_type(t): diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 1b47002e72fc6..24a164aa15427 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2306,7 +2306,7 @@ def maybe_reorder( if any(exclude): arr_exclude = (x for x in exclude if x in arr_columns) - to_remove = {arr_columns.get_loc(col) for col in arr_exclude} + to_remove = {arr_columns.get_loc(col) for col in arr_exclude} # pyright: ignore[reportUnhashable] arrays = [v for i, v in enumerate(arrays) if i not in to_remove] columns = columns.drop(exclude) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 68314567d1b5e..5bf3e0e4de2fb 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -3719,7 +3719,7 @@ def blk_func(values: ArrayLike) -> ArrayLike: mask = isna(values) if values.ndim == 1: indexer = np.empty(values.shape, dtype=np.intp) - col_func(out=indexer, mask=mask) + col_func(out=indexer, mask=mask) # type: ignore[arg-type] return algorithms.take_nd(values, indexer) else: @@ -4081,7 +4081,9 @@ def _nth( def quantile( self, q: float | AnyArrayLike = 0.5, - interpolation: str = "linear", + interpolation: Literal[ + "linear", "lower", "higher", "nearest", "midpoint" + ] = "linear", numeric_only: bool = False, ): """ @@ -4270,7 +4272,7 @@ def blk_func(values: ArrayLike) -> ArrayLike: func( out[0], values=vals, - mask=mask, + mask=mask, # type: ignore[arg-type] result_mask=result_mask, is_datetimelike=is_datetimelike, ) diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index b32119a2ddbde..4c7fe604e452d 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -898,7 +898,7 @@ def _unob_index_and_ids( return unob_index, unob_ids @final - def get_group_levels(self) -> Generator[Index, None, None]: + def get_group_levels(self) -> Generator[Index]: # Note: only called from _insert_inaxis_grouper, which # is only called for BaseGrouper, never for BinGrouper result_index = self.result_index diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 8feac890883eb..94717141b30b0 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -991,7 +991,7 @@ def length(self) -> Index: # -------------------------------------------------------------------- # Set Operations - def _intersection(self, other, sort): + def _intersection(self, other, sort: bool = False): """ intersection specialized to the case with matching dtypes. """ @@ -1006,7 +1006,7 @@ def _intersection(self, other, sort): # duplicates taken = self._intersection_non_unique(other) - if sort is None: + if sort: taken = taken.sort_values() return taken diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 9eccb7645fbe7..ae9b272af9fe9 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -2664,7 +2664,7 @@ def _reorder_ilevels(self, order) -> MultiIndex: def _recode_for_new_levels( self, new_levels, copy: bool = True - ) -> Generator[np.ndarray, None, None]: + ) -> Generator[np.ndarray]: if len(new_levels) > self.nlevels: raise AssertionError( f"Length of new_levels ({len(new_levels)}) " diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index cb40e920149fa..a3ff577966a6d 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -388,7 +388,7 @@ def _split_op_result(self, result: ArrayLike) -> list[Block]: return [nb] @final - def _split(self) -> Generator[Block, None, None]: + def _split(self) -> Generator[Block]: """ Split a block into a list of single-column blocks. """ diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index b96d5a59effce..2ee7d3948a70f 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -250,7 +250,7 @@ def _concat_homogeneous_fastpath( def _get_combined_plan( mgrs: list[BlockManager], -) -> Generator[tuple[BlockPlacement, list[JoinUnit]], None, None]: +) -> Generator[tuple[BlockPlacement, list[JoinUnit]]]: max_len = mgrs[0].shape[0] blknos_list = [mgr.blknos for mgr in mgrs] diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index aa4a785519051..a3738bb25f56c 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -856,7 +856,7 @@ def _slice_take_blocks_ax0( *, use_na_proxy: bool = False, ref_inplace_op: bool = False, - ) -> Generator[Block, None, None]: + ) -> Generator[Block]: """ Slice/take blocks along axis=0. @@ -1731,7 +1731,7 @@ def unstack(self, unstacker, fill_value) -> BlockManager: bm = BlockManager(new_blocks, [new_columns, new_index], verify_integrity=False) return bm - def to_iter_dict(self) -> Generator[tuple[str, Self], None, None]: + def to_iter_dict(self) -> Generator[tuple[str, Self]]: """ Yield a tuple of (str(dtype), BlockManager) diff --git a/pandas/core/methods/to_dict.py b/pandas/core/methods/to_dict.py index 84202a4fcc840..aea95e4684573 100644 --- a/pandas/core/methods/to_dict.py +++ b/pandas/core/methods/to_dict.py @@ -33,7 +33,7 @@ def create_data_for_split( df: DataFrame, are_all_object_dtype_cols: bool, object_dtype_indices: list[int] -) -> Generator[list, None, None]: +) -> Generator[list]: """ Simple helper method to create data for to ``to_dict(orient="split")`` to create the main output data diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 711396096a5e3..42fed83398737 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -404,7 +404,7 @@ def transform(self, arg, *args, **kwargs): arg, *args, **kwargs ) - def _downsample(self, f, **kwargs): + def _downsample(self, how, **kwargs): raise AbstractMethodError(self) def _upsample(self, f, limit: int | None = None, fill_value=None): diff --git a/pandas/core/series.py b/pandas/core/series.py index bbcb6615aeefd..fe2bb0b5aa5c3 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -813,8 +813,7 @@ def _values(self): def _references(self) -> BlockValuesRefs: return self._mgr._block.refs - # error: Decorated property not supported - @Appender(base.IndexOpsMixin.array.__doc__) # type: ignore[misc] + @Appender(base.IndexOpsMixin.array.__doc__) # type: ignore[prop-decorator] @property def array(self) -> ExtensionArray: return self._mgr.array_values() diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 86c7316320f44..4680a63bf57a1 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -1000,7 +1000,7 @@ def to_datetime( dayfirst=dayfirst, yearfirst=yearfirst, errors=errors, - exact=exact, + exact=exact, # type: ignore[arg-type] ) result: Timestamp | NaTType | Series | Index diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 9ea825ad4e44d..cf74cc30f3c5d 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -1507,7 +1507,7 @@ def _generate_cython_apply_func( window_aggregations.roll_apply, args=args, kwargs=kwargs, - raw=raw, + raw=bool(raw), function=function, ) diff --git a/pandas/io/excel/_odswriter.py b/pandas/io/excel/_odswriter.py index 0ddb59d3413ff..10a06aec72a57 100644 --- a/pandas/io/excel/_odswriter.py +++ b/pandas/io/excel/_odswriter.py @@ -34,7 +34,7 @@ class ODSWriter(ExcelWriter): _engine = "odf" _supported_extensions = (".ods",) - def __init__( + def __init__( # pyright: ignore[reportInconsistentConstructor] self, path: FilePath | WriteExcelBuffer | ExcelWriter, engine: str | None = None, diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py index 218a592c22b4a..3055c68a93cbc 100644 --- a/pandas/io/excel/_openpyxl.py +++ b/pandas/io/excel/_openpyxl.py @@ -42,7 +42,7 @@ class OpenpyxlWriter(ExcelWriter): _engine = "openpyxl" _supported_extensions = (".xlsx", ".xlsm") - def __init__( + def __init__( # pyright: ignore[reportInconsistentConstructor] self, path: FilePath | WriteExcelBuffer | ExcelWriter, engine: str | None = None, diff --git a/pandas/io/excel/_xlsxwriter.py b/pandas/io/excel/_xlsxwriter.py index b2fd24a670300..4a7b8eee2bfce 100644 --- a/pandas/io/excel/_xlsxwriter.py +++ b/pandas/io/excel/_xlsxwriter.py @@ -181,7 +181,7 @@ class XlsxWriter(ExcelWriter): _engine = "xlsxwriter" _supported_extensions = (".xlsx",) - def __init__( + def __init__( # pyright: ignore[reportInconsistentConstructor] self, path: FilePath | WriteExcelBuffer | ExcelWriter, engine: str | None = None, diff --git a/pandas/io/formats/css.py b/pandas/io/formats/css.py index 0af04526ea96d..10c970887e03b 100644 --- a/pandas/io/formats/css.py +++ b/pandas/io/formats/css.py @@ -34,9 +34,7 @@ def _side_expander(prop_fmt: str) -> Callable: function: Return to call when a 'border(-{side}): {value}' string is encountered """ - def expand( - self: CSSResolver, prop: str, value: str - ) -> Generator[tuple[str, str], None, None]: + def expand(self: CSSResolver, prop: str, value: str) -> Generator[tuple[str, str]]: """ Expand shorthand property into side-specific property (top, right, bottom, left) @@ -81,9 +79,7 @@ def _border_expander(side: str = "") -> Callable: if side != "": side = f"-{side}" - def expand( - self: CSSResolver, prop: str, value: str - ) -> Generator[tuple[str, str], None, None]: + def expand(self: CSSResolver, prop: str, value: str) -> Generator[tuple[str, str]]: """ Expand border into color, style, and width tuples @@ -392,7 +388,7 @@ def _error() -> str: size_fmt = f"{val:f}pt" return size_fmt - def atomize(self, declarations: Iterable) -> Generator[tuple[str, str], None, None]: + def atomize(self, declarations: Iterable) -> Generator[tuple[str, str]]: for prop, value in declarations: prop = prop.lower() value = value.lower() diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 9ad5ac83e9eae..5aecc6af712e5 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1024,7 +1024,7 @@ def save_to_buffer( @contextmanager def _get_buffer( buf: FilePath | WriteBuffer[str] | None, encoding: str | None = None -) -> Generator[WriteBuffer[str], None, None] | Generator[StringIO, None, None]: +) -> Generator[WriteBuffer[str]] | Generator[StringIO]: """ Context manager to open, yield and close buffer for filenames or Path-like objects, otherwise yield buf unchanged. diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py index 3a2a1c37f1879..99d584db61755 100644 --- a/pandas/io/parsers/python_parser.py +++ b/pandas/io/parsers/python_parser.py @@ -1203,7 +1203,7 @@ def _rows_to_cols(self, content: list[list[Scalar]]) -> list[np.ndarray]: if callable(self.on_bad_lines): new_l = self.on_bad_lines(_content) if new_l is not None: - content.append(new_l) + content.append(new_l) # pyright: ignore[reportArgumentType] elif self.on_bad_lines in ( self.BadLineHandleMethod.ERROR, self.BadLineHandleMethod.WARN, diff --git a/pandas/io/sas/sas7bdat.py b/pandas/io/sas/sas7bdat.py index 25257d5fcc192..c5aab4d967cd4 100644 --- a/pandas/io/sas/sas7bdat.py +++ b/pandas/io/sas/sas7bdat.py @@ -516,7 +516,7 @@ def _process_columntext_subheader(self, offset: int, length: int) -> None: buf = self._read_bytes(offset1, self._lcs) self.creator_proc = buf[0 : self._lcp] if hasattr(self, "creator_proc"): - self.creator_proc = self._convert_header_text(self.creator_proc) + self.creator_proc = self._convert_header_text(self.creator_proc) # pyright: ignore[reportArgumentType] def _process_columnname_subheader(self, offset: int, length: int) -> None: int_len = self._int_length diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 99dd06568fa01..9aff5600cf49b 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -233,7 +233,7 @@ def _wrap_result_adbc( @overload -def read_sql_table( +def read_sql_table( # pyright: ignore[reportOverlappingOverload] table_name: str, con, schema=..., @@ -364,7 +364,7 @@ def read_sql_table( @overload -def read_sql_query( +def read_sql_query( # pyright: ignore[reportOverlappingOverload] sql, con, index_col: str | list[str] | None = ..., @@ -500,7 +500,7 @@ def read_sql_query( @overload -def read_sql( +def read_sql( # pyright: ignore[reportOverlappingOverload] sql, con, index_col: str | list[str] | None = ..., @@ -1119,7 +1119,7 @@ def _query_iterator( coerce_float: bool = True, parse_dates=None, dtype_backend: DtypeBackend | Literal["numpy"] = "numpy", - ) -> Generator[DataFrame, None, None]: + ) -> Generator[DataFrame]: """Return generator through chunked result set.""" has_read_data = False with exit_stack: @@ -1732,7 +1732,7 @@ def _query_iterator( parse_dates=None, dtype: DtypeArg | None = None, dtype_backend: DtypeBackend | Literal["numpy"] = "numpy", - ) -> Generator[DataFrame, None, None]: + ) -> Generator[DataFrame]: """Return generator through chunked result set""" has_read_data = False with exit_stack: @@ -2682,7 +2682,7 @@ def _query_iterator( parse_dates=None, dtype: DtypeArg | None = None, dtype_backend: DtypeBackend | Literal["numpy"] = "numpy", - ) -> Generator[DataFrame, None, None]: + ) -> Generator[DataFrame]: """Return generator through chunked result set""" has_read_data = False while True: diff --git a/pandas/plotting/_matplotlib/converter.py b/pandas/plotting/_matplotlib/converter.py index fc63d65f1e160..4c00049075d03 100644 --- a/pandas/plotting/_matplotlib/converter.py +++ b/pandas/plotting/_matplotlib/converter.py @@ -92,7 +92,7 @@ def wrapper(*args, **kwargs): @contextlib.contextmanager -def pandas_converters() -> Generator[None, None, None]: +def pandas_converters() -> Generator[None]: """ Context manager registering pandas' converters for a plot. @@ -527,7 +527,7 @@ def _get_periods_per_ymd(freq: BaseOffset) -> tuple[int, int, int]: ppd = -1 # placeholder for above-day freqs - if dtype_code >= FreqGroup.FR_HR.value: + if dtype_code >= FreqGroup.FR_HR.value: # pyright: ignore[reportAttributeAccessIssue] # error: "BaseOffset" has no attribute "_creso" ppd = periods_per_day(freq._creso) # type: ignore[attr-defined] ppm = 28 * ppd @@ -684,7 +684,7 @@ def _second_finder(label_interval: int) -> None: elif span <= periodsperyear // 4: month_start = _period_break(dates_, "month") info_maj[month_start] = True - if dtype_code < FreqGroup.FR_HR.value: + if dtype_code < FreqGroup.FR_HR.value: # pyright: ignore[reportAttributeAccessIssue] info["min"] = True else: day_start = _period_break(dates_, "day") @@ -910,7 +910,7 @@ def get_finder(freq: BaseOffset): return _quarterly_finder elif fgroup == FreqGroup.FR_MTH: return _monthly_finder - elif (dtype_code >= FreqGroup.FR_BUS.value) or fgroup == FreqGroup.FR_WK: + elif (dtype_code >= FreqGroup.FR_BUS.value) or fgroup == FreqGroup.FR_WK: # pyright: ignore[reportAttributeAccessIssue] return _daily_finder else: # pragma: no cover raise NotImplementedError(f"Unsupported frequency: {dtype_code}") diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py index f9c370b2486fd..d5624aecd1215 100644 --- a/pandas/plotting/_matplotlib/tools.py +++ b/pandas/plotting/_matplotlib/tools.py @@ -442,7 +442,7 @@ def handle_shared_axes( _remove_labels_from_axis(ax.yaxis) -def flatten_axes(axes: Axes | Iterable[Axes]) -> Generator[Axes, None, None]: +def flatten_axes(axes: Axes | Iterable[Axes]) -> Generator[Axes]: if not is_list_like(axes): yield axes # type: ignore[misc] elif isinstance(axes, (np.ndarray, ABCIndex)): diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py index 81940613dd2b0..7face74dcbc89 100644 --- a/pandas/plotting/_misc.py +++ b/pandas/plotting/_misc.py @@ -715,7 +715,7 @@ def _get_canonical_key(self, key: str) -> str: return self._ALIASES.get(key, key) @contextmanager - def use(self, key, value) -> Generator[_Options, None, None]: + def use(self, key, value) -> Generator[_Options]: """ Temporarily set a parameter value using the with statement. Aliasing allowed. diff --git a/pandas/tests/frame/test_ufunc.py b/pandas/tests/frame/test_ufunc.py index 95b315c32dca5..092e65dd4b431 100644 --- a/pandas/tests/frame/test_ufunc.py +++ b/pandas/tests/frame/test_ufunc.py @@ -66,14 +66,14 @@ def test_binary_input_dispatch_binop(dtype): [ (np.add, 1, [2, 3, 4, 5]), ( - partial(np.add, where=[[False, True], [True, False]]), + partial(np.add, where=[[False, True], [True, False]]), # type: ignore[misc] np.array([[1, 1], [1, 1]]), [0, 3, 4, 0], ), (np.power, np.array([[1, 1], [2, 2]]), [1, 2, 9, 16]), (np.subtract, 2, [-1, 0, 1, 2]), ( - partial(np.negative, where=np.array([[False, True], [True, False]])), + partial(np.negative, where=np.array([[False, True], [True, False]])), # type: ignore[misc] None, [0, -2, -3, 0], ), diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 2b62b384930d6..19b46d9b2c15f 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -1635,7 +1635,7 @@ def test_generated_op_names(opname, index): partial(DatetimeIndex, data=["2020-01-01"]), partial(PeriodIndex, data=["2020-01-01"]), partial(TimedeltaIndex, data=["1 day"]), - partial(RangeIndex, data=range(1)), + partial(RangeIndex, start=range(1)), partial(IntervalIndex, data=[pd.Interval(0, 1)]), partial(Index, data=["a"], dtype=object), partial(MultiIndex, levels=[1], codes=[0]), diff --git a/pandas/util/_exceptions.py b/pandas/util/_exceptions.py index 5f50838d37315..b3c8e54d3ca7f 100644 --- a/pandas/util/_exceptions.py +++ b/pandas/util/_exceptions.py @@ -4,7 +4,10 @@ import inspect import os import re -from typing import TYPE_CHECKING +from typing import ( + TYPE_CHECKING, + Any, +) import warnings if TYPE_CHECKING: @@ -13,7 +16,7 @@ @contextlib.contextmanager -def rewrite_exception(old_name: str, new_name: str) -> Generator[None, None, None]: +def rewrite_exception(old_name: str, new_name: str) -> Generator[None]: """ Rewrite the message of an exception. """ @@ -24,7 +27,7 @@ def rewrite_exception(old_name: str, new_name: str) -> Generator[None, None, Non raise msg = str(err.args[0]) msg = msg.replace(old_name, new_name) - args: tuple[str, ...] = (msg,) + args: tuple[Any, ...] = (msg,) if len(err.args) > 1: args = args + err.args[1:] err.args = args @@ -66,7 +69,7 @@ def rewrite_warning( target_category: type[Warning], new_message: str, new_category: type[Warning] | None = None, -) -> Generator[None, None, None]: +) -> Generator[None]: """ Rewrite the message of a warning. diff --git a/requirements-dev.txt b/requirements-dev.txt index 52d2553fc4001..1bf42af6bf2cd 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -53,10 +53,10 @@ seaborn moto flask asv>=0.6.1 -flake8==6.1.0 -mypy==1.9.0 +flake8==7.1.0 +mypy==1.11.2 tokenize-rt -pre-commit>=3.6.0 +pre-commit>=4.0.1 gitpython gitdb google-auth