diff --git a/pandas-stubs/_libs/interval.pyi b/pandas-stubs/_libs/interval.pyi index 5913da7da..05cefab49 100644 --- a/pandas-stubs/_libs/interval.pyi +++ b/pandas-stubs/_libs/interval.pyi @@ -25,7 +25,9 @@ VALID_CLOSED: frozenset[str] _OrderableScalarT = TypeVar("_OrderableScalarT", bound=int | float) _OrderableTimesT = TypeVar("_OrderableTimesT", bound=Timestamp | Timedelta) -_OrderableT = TypeVar("_OrderableT", bound=int | float | Timestamp | Timedelta) +_OrderableT = TypeVar( + "_OrderableT", bound=int | float | Timestamp | Timedelta, default=Any +) @type_check_only class _LengthDescriptor: diff --git a/pandas-stubs/_typing.pyi b/pandas-stubs/_typing.pyi index 343e8831e..417144319 100644 --- a/pandas-stubs/_typing.pyi +++ b/pandas-stubs/_typing.pyi @@ -774,7 +774,7 @@ XMLParsers: TypeAlias = Literal["lxml", "etree"] HTMLFlavors: TypeAlias = Literal["lxml", "html5lib", "bs4"] # Interval closed type -IntervalT = TypeVar("IntervalT", bound=Interval) +IntervalT = TypeVar("IntervalT", bound=Interval, default=Interval) IntervalLeftRight: TypeAlias = Literal["left", "right"] IntervalClosedType: TypeAlias = IntervalLeftRight | Literal["both", "neither"] @@ -959,7 +959,10 @@ np_1darray_dt: TypeAlias = np_1darray[np.datetime64] np_1darray_td: TypeAlias = np_1darray[np.timedelta64] np_2darray: TypeAlias = np.ndarray[tuple[int, int], np.dtype[GenericT]] -NDArrayT = TypeVar("NDArrayT", bound=np.ndarray) +if sys.version_info >= (3, 11): + NDArrayT = TypeVar("NDArrayT", bound=np.ndarray) +else: + NDArrayT = TypeVar("NDArrayT", bound=np.ndarray[Any, Any]) DtypeNp = TypeVar("DtypeNp", bound=np.dtype[np.generic]) KeysArgType: TypeAlias = Any @@ -1070,7 +1073,7 @@ if TYPE_CHECKING: # noqa: PYI002 | Scalar | Period | Interval[int | float | Timestamp | Timedelta] - | tuple, + | tuple[Any, ...], ) # Use a distinct SeriesByT when using groupby with Series of known dtype. # Essentially, an intersection between Series S1 TypeVar, and ByT TypeVar @@ -1102,7 +1105,7 @@ GroupByObjectNonScalar: TypeAlias = ( | Grouper | list[Grouper] ) -GroupByObject: TypeAlias = Scalar | Index | GroupByObjectNonScalar | Series +GroupByObject: TypeAlias = Scalar | Index | GroupByObjectNonScalar[_HashableTa] | Series StataDateFormat: TypeAlias = Literal[ "tc", @@ -1125,9 +1128,9 @@ StataDateFormat: TypeAlias = Literal[ # `DataFrame.replace` also accepts mappings of these. ReplaceValue: TypeAlias = ( Scalar - | Pattern + | Pattern[Any] | NAType - | Sequence[Scalar | Pattern] + | Sequence[Scalar | Pattern[Any]] | Mapping[HashableT, ScalarT] | Series | None diff --git a/pandas-stubs/core/arrays/base.pyi b/pandas-stubs/core/arrays/base.pyi index 7ce4f26c6..911b2df86 100644 --- a/pandas-stubs/core/arrays/base.pyi +++ b/pandas-stubs/core/arrays/base.pyi @@ -2,6 +2,7 @@ from collections.abc import ( Iterator, Sequence, ) +import sys from typing import ( Any, Literal, @@ -55,8 +56,13 @@ class ExtensionArray: def ndim(self) -> int: ... @property def nbytes(self) -> int: ... - @overload - def astype(self, dtype: np.dtype, copy: bool = True) -> np_1darray: ... + if sys.version_info >= (3, 11): + @overload + def astype(self, dtype: np.dtype, copy: bool = True) -> np_1darray: ... + else: + @overload + def astype(self, dtype: np.dtype[Any], copy: bool = True) -> np_1darray: ... + @overload def astype(self, dtype: ExtensionDtype, copy: bool = True) -> ExtensionArray: ... @overload diff --git a/pandas-stubs/core/arrays/datetimes.pyi b/pandas-stubs/core/arrays/datetimes.pyi index 82d884fe6..79b36c0f3 100644 --- a/pandas-stubs/core/arrays/datetimes.pyi +++ b/pandas-stubs/core/arrays/datetimes.pyi @@ -1,4 +1,6 @@ from datetime import tzinfo as _tzinfo +import sys +from typing import Any import numpy as np from pandas.core.arrays.datetimelike import ( @@ -19,8 +21,13 @@ class DatetimeArray(DatetimeLikeArrayMixin, TimelikeOps, DatelikeOps): __array_priority__: int = ... def __init__(self, values, dtype=..., freq=..., copy: bool = ...) -> None: ... # ignore in dtype() is from the pandas source - @property - def dtype(self) -> np.dtype | DatetimeTZDtype: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + if sys.version_info >= (3, 11): + @property + def dtype(self) -> np.dtype | DatetimeTZDtype: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + else: + @property + def dtype(self) -> np.dtype[Any] | DatetimeTZDtype: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + @property def tz(self): ... @tz.setter diff --git a/pandas-stubs/core/arrays/numpy_.pyi b/pandas-stubs/core/arrays/numpy_.pyi index 760d82e84..4081a6766 100644 --- a/pandas-stubs/core/arrays/numpy_.pyi +++ b/pandas-stubs/core/arrays/numpy_.pyi @@ -1,3 +1,6 @@ +import sys +from typing import Any + import numpy as np from numpy.lib.mixins import NDArrayOperatorsMixin from pandas.core.arrays.base import ( @@ -8,8 +11,13 @@ from pandas.core.arrays.base import ( from pandas.core.dtypes.dtypes import ExtensionDtype class PandasDtype(ExtensionDtype): - @property - def numpy_dtype(self) -> np.dtype: ... + if sys.version_info >= (3, 11): + @property + def numpy_dtype(self) -> np.dtype: ... + else: + @property + def numpy_dtype(self) -> np.dtype[Any]: ... + @property def itemsize(self) -> int: ... diff --git a/pandas-stubs/core/computation/ops.pyi b/pandas-stubs/core/computation/ops.pyi index 69be2f864..7cc0f95f9 100644 --- a/pandas-stubs/core/computation/ops.pyi +++ b/pandas-stubs/core/computation/ops.pyi @@ -1,3 +1,4 @@ +import sys from typing import Any import numpy as np @@ -75,8 +76,12 @@ class UnaryOp(Op): func = ... def __init__(self, op: str, operand) -> None: ... def __call__(self, env): ... - @property - def return_type(self) -> np.dtype: ... + if sys.version_info >= (3, 11): + @property + def return_type(self) -> np.dtype: ... + else: + @property + def return_type(self) -> np.dtype[Any]: ... class MathCall(Op): func = ... diff --git a/pandas-stubs/core/construction.pyi b/pandas-stubs/core/construction.pyi index 3638fac78..c677f1cb9 100644 --- a/pandas-stubs/core/construction.pyi +++ b/pandas-stubs/core/construction.pyi @@ -1,5 +1,9 @@ from collections.abc import Sequence -from typing import overload +import sys +from typing import ( + Any, + overload, +) import numpy as np from pandas.core.arrays.base import ExtensionArray @@ -40,9 +44,19 @@ def array( dtype: PandasFloatDtypeArg | None = None, copy: bool = True, ) -> FloatingArray: ... -@overload -def array( - data: Sequence[object], - dtype: str | np.dtype | ExtensionDtype | None = None, - copy: bool = True, -) -> ExtensionArray: ... + +if sys.version_info >= (3, 11): + @overload + def array( + data: Sequence[object], + dtype: str | np.dtype | ExtensionDtype | None = None, + copy: bool = True, + ) -> ExtensionArray: ... + +else: + @overload + def array( + data: Sequence[object], + dtype: str | np.dtype[Any] | ExtensionDtype | None = None, + copy: bool = True, + ) -> ExtensionArray: ... diff --git a/pandas-stubs/core/dtypes/dtypes.pyi b/pandas-stubs/core/dtypes/dtypes.pyi index 3826e7d2a..73be65dcf 100644 --- a/pandas-stubs/core/dtypes/dtypes.pyi +++ b/pandas-stubs/core/dtypes/dtypes.pyi @@ -1,4 +1,5 @@ import datetime as dt +import sys from typing import ( Any, Literal, @@ -59,5 +60,9 @@ class PeriodDtype(PandasExtensionDtype): class IntervalDtype(PandasExtensionDtype): def __init__(self, subtype: str | npt.DTypeLike | None = ...) -> None: ... - @property - def subtype(self) -> np.dtype | None: ... + if sys.version_info >= (3, 11): + @property + def subtype(self) -> np.dtype | None: ... + else: + @property + def subtype(self) -> np.dtype[Any] | None: ... diff --git a/pandas-stubs/core/frame.pyi b/pandas-stubs/core/frame.pyi index c45da47c1..e9fc8bf4a 100644 --- a/pandas-stubs/core/frame.pyi +++ b/pandas-stubs/core/frame.pyi @@ -178,7 +178,7 @@ from pandas.plotting import PlotAccessor from pandas.plotting._core import _BoxPlotT _T_MUTABLE_MAPPING_co = TypeVar( - "_T_MUTABLE_MAPPING_co", bound=MutableMapping, covariant=True + "_T_MUTABLE_MAPPING_co", bound=MutableMapping[Any, Any], covariant=True ) class _iLocIndexerFrame(_iLocIndexer, Generic[_T]): @@ -484,7 +484,7 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack): self, orient: str = ..., *, - into: type[defaultdict], + into: type[defaultdict[Any, Any]], index: Literal[True] = True, ) -> Never: ... @overload @@ -500,7 +500,7 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack): self, orient: Literal["records"], *, - into: type[dict] = ..., + into: type[dict[Any, Any]] = ..., index: Literal[True] = True, ) -> list[dict[Hashable, Any]]: ... @overload @@ -516,7 +516,7 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack): self, orient: Literal["index"], *, - into: OrderedDict | type[OrderedDict], + into: OrderedDict[Any, Any] | type[OrderedDict[Any, Any]], index: Literal[True] = True, ) -> OrderedDict[Hashable, dict[Hashable, Any]]: ... @overload @@ -524,7 +524,7 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack): self, orient: Literal["index"], *, - into: type[MutableMapping], + into: type[MutableMapping[Any, Any]], index: Literal[True] = True, ) -> MutableMapping[Hashable, dict[Hashable, Any]]: ... @overload @@ -532,7 +532,7 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack): self, orient: Literal["index"], *, - into: type[dict] = ..., + into: type[dict[Any, Any]] = ..., index: Literal[True] = True, ) -> dict[Hashable, dict[Hashable, Any]]: ... @overload @@ -548,7 +548,7 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack): self, orient: Literal["dict", "list", "series"] = ..., *, - into: type[dict] = ..., + into: type[dict[Any, Any]] = ..., index: Literal[True] = True, ) -> dict[Hashable, Any]: ... @overload @@ -556,7 +556,7 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack): self, orient: Literal["split", "tight"], *, - into: MutableMapping[Any, Any] | type[MutableMapping], + into: MutableMapping[Any, Any] | type[MutableMapping[Any, Any]], index: bool = ..., ) -> MutableMapping[str, list[Any]]: ... @overload @@ -564,7 +564,7 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack): self, orient: Literal["split", "tight"], *, - into: type[dict] = ..., + into: type[dict[Any, Any]] = ..., index: bool = ..., ) -> dict[str, list[Any]]: ... @classmethod @@ -583,16 +583,29 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack): coerce_float: bool = False, nrows: int | None = None, ) -> Self: ... - def to_records( - self, - index: _bool = True, - column_dtypes: ( - _str | npt.DTypeLike | Mapping[HashableT1, npt.DTypeLike] | None - ) = None, - index_dtypes: ( - _str | npt.DTypeLike | Mapping[HashableT2, npt.DTypeLike] | None - ) = None, - ) -> np.recarray: ... + if sys.version_info >= (3, 11): + def to_records( + self, + index: _bool = True, + column_dtypes: ( + _str | npt.DTypeLike | Mapping[HashableT1, npt.DTypeLike] | None + ) = None, + index_dtypes: ( + _str | npt.DTypeLike | Mapping[HashableT2, npt.DTypeLike] | None + ) = None, + ) -> np.recarray: ... + else: + def to_records( + self, + index: _bool = True, + column_dtypes: ( + _str | npt.DTypeLike | Mapping[HashableT1, npt.DTypeLike] | None + ) = None, + index_dtypes: ( + _str | npt.DTypeLike | Mapping[HashableT2, npt.DTypeLike] | None + ) = None, + ) -> np.recarray[Any, Any]: ... + @overload def to_stata( self, @@ -1052,21 +1065,33 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack): @overload def replace( self, - to_replace: ReplaceValue | Mapping[HashableT2, ReplaceValue] = ..., - value: ReplaceValue | Mapping[HashableT3, ReplaceValue] = ..., + to_replace: ( + ReplaceValue[Any, Any] | Mapping[HashableT2, ReplaceValue[Any, Any]] + ) = ..., + value: ( + ReplaceValue[Any, Any] | Mapping[HashableT3, ReplaceValue[Any, Any]] + ) = ..., *, inplace: Literal[True], - regex: ReplaceValue | Mapping[HashableT3, ReplaceValue] = ..., + regex: ( + ReplaceValue[Any, Any] | Mapping[HashableT3, ReplaceValue[Any, Any]] + ) = ..., # TODO: pandas-dev/pandas#63195 return Self after Pandas 3.0 ) -> None: ... @overload def replace( self, - to_replace: ReplaceValue | Mapping[HashableT2, ReplaceValue] = ..., - value: ReplaceValue | Mapping[HashableT3, ReplaceValue] = ..., + to_replace: ( + ReplaceValue[Any, Any] | Mapping[HashableT2, ReplaceValue[Any, Any]] + ) = ..., + value: ( + ReplaceValue[Any, Any] | Mapping[HashableT3, ReplaceValue[Any, Any]] + ) = ..., *, inplace: Literal[False] = False, - regex: ReplaceValue | Mapping[HashableT3, ReplaceValue] = ..., + regex: ( + ReplaceValue[Any, Any] | Mapping[HashableT3, ReplaceValue[Any, Any]] + ) = ..., ) -> Self: ... def shift( self, @@ -1381,7 +1406,7 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack): dropna: _bool = ..., ) -> DataFrameGroupBy[Period, Literal[False]]: ... @overload - def groupby( # pyright: ignore reportOverlappingOverload + def groupby( self, by: IntervalIndex[IntervalT], level: IndexLabel | None = ..., @@ -1394,7 +1419,7 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack): @overload def groupby( self, - by: IntervalIndex[IntervalT], + by: IntervalIndex, level: IndexLabel | None = ..., as_index: Literal[False] = False, sort: _bool = ..., @@ -1405,7 +1430,7 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack): @overload def groupby( # type: ignore[overload-overlap] # pyright: ignore reportOverlappingOverload self, - by: MultiIndex | GroupByObjectNonScalar | None = ..., + by: MultiIndex | GroupByObjectNonScalar[Any] | None = ..., level: IndexLabel | None = ..., as_index: Literal[True] = True, sort: _bool = ..., @@ -1416,7 +1441,7 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack): @overload def groupby( # type: ignore[overload-overlap] self, - by: MultiIndex | GroupByObjectNonScalar | None = ..., + by: MultiIndex | GroupByObjectNonScalar[Any] | None = ..., level: IndexLabel | None = ..., as_index: Literal[False] = False, sort: _bool = ..., @@ -1477,11 +1502,17 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack): ) -> Self: ... def pivot_table( self, - values: _PivotTableValuesTypes = None, - index: _PivotTableIndexTypes = None, - columns: _PivotTableColumnsTypes = None, + values: _PivotTableValuesTypes[ + Any # ty: ignore[invalid-type-arguments] + ] = None, + index: _PivotTableIndexTypes[Any] = None, # ty: ignore[invalid-type-arguments] + columns: _PivotTableColumnsTypes[ + Any # ty: ignore[invalid-type-arguments] + ] = None, aggfunc: ( - _PivotAggFunc | Sequence[_PivotAggFunc] | Mapping[Hashable, _PivotAggFunc] + _PivotAggFunc[Any] + | Sequence[_PivotAggFunc[Any]] + | Mapping[Hashable, _PivotAggFunc[Any]] ) = "mean", fill_value: Scalar | None = None, margins: _bool = False, @@ -1876,7 +1907,7 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack): @overload def boxplot( self, - by: Hashable | ListLikeHashable, + by: Hashable | ListLikeHashable[Any], ax: PlotAxes | None = None, fontsize: float | _str | None = None, rot: float = 0, @@ -1891,7 +1922,7 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack): @overload def boxplot( self, - by: Hashable | ListLikeHashable, + by: Hashable | ListLikeHashable[Any], ax: PlotAxes | None = None, fontsize: float | _str | None = None, rot: float = 0, @@ -2634,7 +2665,7 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack): **kwargs: Any, ) -> Series: ... # Not actually positional, but used to handle removal of deprecated - def set_axis(self, labels: AxesData, *, axis: Axis = 0) -> Self: ... + def set_axis(self, labels: AxesData[Any], *, axis: Axis = 0) -> Self: ... def skew( self, axis: Axis | None = ..., @@ -2863,8 +2894,12 @@ class DataFrame(NDFrame, OpsMixin, _GetItemHack): def __rfloordiv__( self, other: float | DataFrame | Series[int] | Series[float] | Sequence[float] ) -> Self: ... - def __truediv__(self, other: float | DataFrame | Series | Sequence) -> Self: ... - def __rtruediv__(self, other: float | DataFrame | Series | Sequence) -> Self: ... + def __truediv__( + self, other: float | DataFrame | Series | Sequence[Any] + ) -> Self: ... + def __rtruediv__( + self, other: float | DataFrame | Series | Sequence[Any] + ) -> Self: ... @final def __bool__(self) -> NoReturn: ... diff --git a/pandas-stubs/core/groupby/groupby.pyi b/pandas-stubs/core/groupby/groupby.pyi index 75d3265b0..e27e3103c 100644 --- a/pandas-stubs/core/groupby/groupby.pyi +++ b/pandas-stubs/core/groupby/groupby.pyi @@ -7,6 +7,7 @@ from collections.abc import ( ) import datetime as dt from typing import ( + TYPE_CHECKING, Any, Concatenate, Generic, @@ -70,11 +71,12 @@ from pandas._typing import ( from pandas.plotting import PlotAccessor -_ResamplerGroupBy: TypeAlias = ( - DatetimeIndexResamplerGroupby[NDFrameT] # ty: ignore[invalid-argument-type] - | PeriodIndexResamplerGroupby[NDFrameT] # ty: ignore[invalid-argument-type] - | TimedeltaIndexResamplerGroupby[NDFrameT] # ty: ignore[invalid-argument-type] -) +if TYPE_CHECKING: # noqa: PYI002 + _ResamplerGroupBy: TypeAlias = ( + DatetimeIndexResamplerGroupby[NDFrameT] # ty: ignore[invalid-argument-type] + | PeriodIndexResamplerGroupby[NDFrameT] # ty: ignore[invalid-argument-type] + | TimedeltaIndexResamplerGroupby[NDFrameT] # ty: ignore[invalid-argument-type] + ) class GroupBy(BaseGroupBy[NDFrameT]): def __getattr__(self, attr: str) -> Any: ... @@ -338,7 +340,7 @@ class GroupBy(BaseGroupBy[NDFrameT]): random_state: RandomState | None = ..., ) -> NDFrameT: ... -_GroupByT = TypeVar("_GroupByT", bound=GroupBy) +_GroupByT = TypeVar("_GroupByT", bound=GroupBy[Any]) # GroupByPlot does not really inherit from PlotAccessor but it delegates # to it using __call__ and __getattr__. We lie here to avoid repeating the @@ -383,15 +385,15 @@ class BaseGroupBy(SelectionMixin[NDFrameT], GroupByIndexingMixin): @final def __iter__(self) -> Iterator[tuple[Hashable, NDFrameT]]: ... @overload - def __getitem__(self: BaseGroupBy[DataFrame], key: Scalar) -> generic.SeriesGroupBy: ... # type: ignore[overload-overlap] # pyright: ignore[reportOverlappingOverload] + def __getitem__(self: BaseGroupBy[DataFrame], key: Scalar) -> generic.SeriesGroupBy[Any, Any]: ... # type: ignore[overload-overlap] # pyright: ignore[reportOverlappingOverload] @overload def __getitem__( self: BaseGroupBy[DataFrame], key: Iterable[Hashable] - ) -> generic.DataFrameGroupBy: ... + ) -> generic.DataFrameGroupBy[Any, Any]: ... @overload def __getitem__( self: BaseGroupBy[Series[S1]], idx: list[str] | Index | Series[S1] | MaskType | tuple[Hashable | slice, ...], - ) -> generic.SeriesGroupBy: ... + ) -> generic.SeriesGroupBy[Any, Any]: ... @overload def __getitem__(self: BaseGroupBy[Series[S1]], idx: Scalar) -> S1: ... diff --git a/pandas-stubs/core/indexes/accessors.pyi b/pandas-stubs/core/indexes/accessors.pyi index 61d24d45c..7b46576d8 100644 --- a/pandas-stubs/core/indexes/accessors.pyi +++ b/pandas-stubs/core/indexes/accessors.pyi @@ -5,6 +5,7 @@ from datetime import ( tzinfo as _tzinfo, ) from typing import ( + Any, Generic, Literal, TypeVar, @@ -377,7 +378,7 @@ class PeriodProperties( Series[Timestamp], Series[int], Series[str], DatetimeArray, PeriodArray ], _DatetimeFieldOps[Series[int]], - _IsLeapYearProperty, + _IsLeapYearProperty[_DTBoolOpsReturnType], _FreqProperty[BaseOffset], ): ... class CombinedDatetimelikeProperties( @@ -393,7 +394,9 @@ class CombinedDatetimelikeProperties( Series[Period], ], _TimedeltaPropertiesNoRounding[Series[int], Series[float]], - _PeriodProperties, + _PeriodProperties[ + Series[Timestamp], Series[int], Series[str], DatetimeArray, PeriodArray + ], ): ... @type_check_only @@ -458,7 +461,7 @@ class DtDescriptor: @overload def __get__( self, instance: Series[Period], owner: type[Series] - ) -> PeriodProperties: ... + ) -> PeriodProperties[Any]: ... @type_check_only class ArrayDescriptor: diff --git a/pandas-stubs/core/indexes/base.pyi b/pandas-stubs/core/indexes/base.pyi index 3f3332940..4e02ad79a 100644 --- a/pandas-stubs/core/indexes/base.pyi +++ b/pandas-stubs/core/indexes/base.pyi @@ -10,6 +10,7 @@ from datetime import ( timedelta, ) from pathlib import Path +import sys from typing import ( Any, ClassVar, @@ -171,7 +172,7 @@ class Index(IndexOpsMixin[S1], ElementOpsMixin[S1]): @overload def __new__( cls, - data: AxesData, + data: AxesData[Any], *, dtype: Literal["int"] | type_t[int | np.integer], copy: bool = ..., @@ -190,7 +191,7 @@ class Index(IndexOpsMixin[S1], ElementOpsMixin[S1]): @overload def __new__( cls, - data: AxesData, + data: AxesData[Any], dtype: FloatNotNumpy16DtypeArg, copy: bool = ..., name: Hashable = ..., @@ -213,7 +214,7 @@ class Index(IndexOpsMixin[S1], ElementOpsMixin[S1]): @overload def __new__( cls, - data: AxesData, + data: AxesData[Any], *, dtype: Literal["complex"] | type_t[complex | np.complexfloating], copy: bool = ..., @@ -236,7 +237,7 @@ class Index(IndexOpsMixin[S1], ElementOpsMixin[S1]): @overload def __new__( cls, - data: AxesData, + data: AxesData[Any], *, dtype: TimestampDtypeArg, copy: bool = ..., @@ -256,7 +257,7 @@ class Index(IndexOpsMixin[S1], ElementOpsMixin[S1]): @overload def __new__( cls, - data: AxesData, + data: AxesData[Any], *, dtype: PeriodDtype, copy: bool = ..., @@ -276,7 +277,7 @@ class Index(IndexOpsMixin[S1], ElementOpsMixin[S1]): @overload def __new__( cls, - data: AxesData, + data: AxesData[Any], *, dtype: TimedeltaDtypeArg, copy: bool = ..., @@ -286,7 +287,7 @@ class Index(IndexOpsMixin[S1], ElementOpsMixin[S1]): @overload def __new__( cls, - data: AxesData, + data: AxesData[Any], *, dtype: CategoryDtypeArg, copy: bool = ..., @@ -306,13 +307,13 @@ class Index(IndexOpsMixin[S1], ElementOpsMixin[S1]): @overload def __new__( cls, - data: AxesData, + data: AxesData[Any], *, dtype: Literal["Interval"], copy: bool = ..., name: Hashable = ..., tupleize_cols: bool = ..., - ) -> IntervalIndex[Interval[Any]]: ... + ) -> IntervalIndex[Interval[_OrderableT]]: ... @overload def __new__( cls, @@ -337,7 +338,7 @@ class Index(IndexOpsMixin[S1], ElementOpsMixin[S1]): @overload def __new__( cls, - data: AxesData = ..., + data: AxesData[Any] = ..., *, dtype: type[S1], copy: bool = ..., @@ -348,7 +349,7 @@ class Index(IndexOpsMixin[S1], ElementOpsMixin[S1]): @overload def __new__( cls, - data: AxesData, + data: AxesData[Any], *, dtype: Dtype = ..., copy: bool = ..., @@ -371,9 +372,15 @@ class Index(IndexOpsMixin[S1], ElementOpsMixin[S1]): @final def is_(self, other: Any) -> bool: ... def __len__(self) -> int: ... - def __array__( - self, dtype: _str | np.dtype = ..., copy: bool | None = ... - ) -> np_1darray: ... + if sys.version_info >= (3, 11): + def __array__( + self, dtype: _str | np.dtype = ..., copy: bool | None = ... + ) -> np_1darray: ... + else: + def __array__( + self, dtype: _str | np.dtype[Any] = ..., copy: bool | None = ... + ) -> np_1darray: ... + @property def dtype(self) -> DtypeObj: ... @final diff --git a/pandas-stubs/core/indexes/datetimes.pyi b/pandas-stubs/core/indexes/datetimes.pyi index 193a37a33..20db7515a 100644 --- a/pandas-stubs/core/indexes/datetimes.pyi +++ b/pandas-stubs/core/indexes/datetimes.pyi @@ -8,7 +8,9 @@ from datetime import ( timedelta, tzinfo as _tzinfo, ) +import sys from typing import ( + Any, final, overload, ) @@ -49,7 +51,7 @@ class DatetimeIndex( ): def __new__( cls, - data: AxesData, + data: AxesData[Any], freq: Frequency = ..., tz: TimeZones = ..., ambiguous: str = ..., @@ -103,8 +105,13 @@ class DatetimeIndex( def isocalendar(self) -> DataFrame: ... @property def tzinfo(self) -> _tzinfo | None: ... - @property - def dtype(self) -> np.dtype | DatetimeTZDtype: ... + if sys.version_info >= (3, 11): + @property + def dtype(self) -> np.dtype | DatetimeTZDtype: ... + else: + @property + def dtype(self) -> np.dtype[Any] | DatetimeTZDtype: ... + def shift( self, periods: int = 1, freq: Frequency | timedelta | None = None ) -> Self: ... diff --git a/pandas-stubs/core/indexes/interval.pyi b/pandas-stubs/core/indexes/interval.pyi index 36b992d70..bb2eecc12 100644 --- a/pandas-stubs/core/indexes/interval.pyi +++ b/pandas-stubs/core/indexes/interval.pyi @@ -208,7 +208,9 @@ class IntervalIndex(ExtensionIndex[IntervalT, np.object_], IntervalMixin): def __contains__(self, key: IntervalT) -> bool: ... # type: ignore[overload-overlap] # pyright: ignore[reportOverlappingOverload] @overload def __contains__(self, key: object) -> Literal[False]: ... - def astype(self, dtype: DtypeArg, copy: bool = True) -> IntervalIndex: ... + def astype( # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + self, dtype: DtypeArg, copy: bool = True + ) -> IntervalIndex: ... @property def inferred_type(self) -> str: ... def memory_usage(self, deep: bool = False) -> int: ... diff --git a/pandas-stubs/core/indexes/multi.pyi b/pandas-stubs/core/indexes/multi.pyi index 144abeecb..b7de51d47 100644 --- a/pandas-stubs/core/indexes/multi.pyi +++ b/pandas-stubs/core/indexes/multi.pyi @@ -5,6 +5,7 @@ from collections.abc import ( Mapping, Sequence, ) +import sys from typing import ( Any, overload, @@ -116,8 +117,13 @@ class MultiIndex(Index): self, names: SequenceNotStr[Hashable] = ..., deep: bool = False ) -> Self: ... def view(self, cls: NumpyNotTimeDtypeArg | NumpyTimedeltaDtypeArg | NumpyTimestampDtypeArg | type[np_ndarray] | None = None) -> MultiIndex: ... # type: ignore[override] # pyrefly: ignore[bad-override] # pyright: ignore[reportIncompatibleMethodOverride] - @property - def dtype(self) -> np.dtype: ... + if sys.version_info >= (3, 11): + @property + def dtype(self) -> np.dtype: ... + else: + @property + def dtype(self) -> np.dtype[Any]: ... + @property def dtypes(self) -> pd.Series[Dtype]: ... def memory_usage(self, deep: bool = False) -> int: ... diff --git a/pandas-stubs/core/indexes/range.pyi b/pandas-stubs/core/indexes/range.pyi index 691d7c26d..3c9814420 100644 --- a/pandas-stubs/core/indexes/range.pyi +++ b/pandas-stubs/core/indexes/range.pyi @@ -2,6 +2,7 @@ from collections.abc import ( Hashable, Sequence, ) +import sys from typing import ( Any, overload, @@ -50,8 +51,13 @@ class RangeIndex(_IndexSubclassBase[int, np.int64]): @property def nbytes(self) -> int: ... def memory_usage(self, deep: bool = ...) -> int: ... - @property - def dtype(self) -> np.dtype: ... + if sys.version_info >= (3, 11): + @property + def dtype(self) -> np.dtype: ... + else: + @property + def dtype(self) -> np.dtype[Any]: ... + @property def is_unique(self) -> bool: ... @property diff --git a/pandas-stubs/core/indexes/timedeltas.pyi b/pandas-stubs/core/indexes/timedeltas.pyi index f9e0a17ed..93be97492 100644 --- a/pandas-stubs/core/indexes/timedeltas.pyi +++ b/pandas-stubs/core/indexes/timedeltas.pyi @@ -7,6 +7,7 @@ from datetime import ( timedelta, ) from typing import ( + Any, Literal, TypeAlias, final, @@ -59,7 +60,9 @@ class TimedeltaIndex( ): def __new__( cls, - data: Sequence[timedelta | Timedelta | np.timedelta64 | float] | AxesData = ..., + data: ( + Sequence[timedelta | Timedelta | np.timedelta64 | float] | AxesData[Any] + ) = ..., freq: Frequency = ..., closed: object = ..., dtype: Literal[" SeriesGroupBy: ... + def __getattr__(self, attr: str) -> SeriesGroupBy[Any, Any]: ... @overload def aggregate( self: Resampler[DataFrame], diff --git a/pandas-stubs/core/series.pyi b/pandas-stubs/core/series.pyi index 469d44ea0..257b7b0ce 100644 --- a/pandas-stubs/core/series.pyi +++ b/pandas-stubs/core/series.pyi @@ -347,7 +347,7 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): def __new__( cls, data: Sequence[Never], - index: AxesData | None = None, + index: AxesData[Any] | None = None, dtype: None = None, name: Hashable = None, copy: bool | None = None, @@ -356,7 +356,7 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): def __new__( cls, data: Sequence[list[_str]], - index: AxesData | None = None, + index: AxesData[Any] | None = None, dtype: None = None, name: Hashable = None, copy: bool | None = None, @@ -365,7 +365,7 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): def __new__( cls, data: Sequence[_str], - index: AxesData | None = None, + index: AxesData[Any] | None = None, dtype: Dtype | None = None, name: Hashable = None, copy: bool | None = None, @@ -381,7 +381,7 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): | datetime | date ), - index: AxesData | None = None, + index: AxesData[Any] | None = None, dtype: TimestampDtypeArg = ..., name: Hashable = None, copy: bool | None = None, @@ -390,7 +390,7 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): def __new__( cls, data: Sequence[datetime | np.timedelta64] | np_ndarray_dt | DatetimeArray, - index: AxesData | None = None, + index: AxesData[Any] | None = None, *, dtype: TimestampDtypeArg, name: Hashable = None, @@ -400,7 +400,7 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): def __new__( cls, data: _DataLike, - index: AxesData | None = None, + index: AxesData[Any] | None = None, *, dtype: CategoryDtypeArg, name: Hashable = None, @@ -410,7 +410,7 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): def __new__( cls, data: PeriodIndex | Sequence[Period], - index: AxesData | None = None, + index: AxesData[Any] | None = None, dtype: PeriodDtype = ..., name: Hashable = None, copy: bool | None = None, @@ -419,7 +419,7 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): def __new__( cls, data: Sequence[BaseOffset], - index: AxesData | None = None, + index: AxesData[Any] | None = None, dtype: PeriodDtype = ..., name: Hashable = None, copy: bool | None = None, @@ -434,7 +434,7 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): | np.timedelta64 | timedelta ), - index: AxesData | None = None, + index: AxesData[Any] | None = None, dtype: TimedeltaDtypeArg = ..., name: Hashable = None, copy: bool | None = None, @@ -446,9 +446,9 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): IntervalIndex[Interval[_OrderableT]] | Interval[_OrderableT] | Sequence[Interval[_OrderableT]] - | dict[HashableT1, Interval[_OrderableT]] + | dict[Hashable, Interval[_OrderableT]] ), - index: AxesData | None = None, + index: AxesData[Any] | None = None, dtype: Literal["Interval"] = ..., name: Hashable = None, copy: bool | None = None, @@ -457,7 +457,7 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): def __new__( # type: ignore[overload-overlap] # pyright: ignore[reportOverlappingOverload] cls, data: Scalar | _DataLike | dict[HashableT1, Any] | None, - index: AxesData | None = None, + index: AxesData[Any] | None = None, *, dtype: type[S1], name: Hashable = None, @@ -467,7 +467,7 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): def __new__( # pyright: ignore[reportOverlappingOverload] cls, data: Sequence[bool | np.bool], - index: AxesData | None = None, + index: AxesData[Any] | None = None, dtype: BooleanDtypeArg | None = None, name: Hashable = None, copy: bool | None = None, @@ -476,7 +476,7 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): def __new__( cls, data: Sequence[int | np.integer], - index: AxesData | None = None, + index: AxesData[Any] | None = None, dtype: IntDtypeArg | UIntDtypeArg | None = None, name: Hashable = None, copy: bool | None = None, @@ -485,7 +485,7 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): def __new__( cls, data: Sequence[float | np.floating] | np_ndarray_float | FloatingArray, - index: AxesData | None = None, + index: AxesData[Any] | None = None, dtype: None = None, name: Hashable = None, copy: bool | None = None, @@ -493,7 +493,7 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): @overload def __new__( cls, - data: AxesData, + data: AxesData[Any], index: None = None, *, dtype: FloatDtypeArg, @@ -503,8 +503,8 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): @overload def __new__( cls, - data: AxesData, - index: AxesData, + data: AxesData[Any], + index: AxesData[Any], dtype: FloatDtypeArg, name: Hashable = None, copy: bool | None = None, @@ -522,7 +522,7 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): | KeysView[S1] | ValuesView[S1] ), - index: AxesData | None = None, + index: AxesData[Any] | None = None, dtype: Dtype | None = None, name: Hashable = None, copy: bool | None = None, @@ -534,12 +534,12 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): Scalar | _DataLike | Mapping[HashableT1, Any] - | BaseGroupBy + | BaseGroupBy[Any] | NaTType | NAType | None ) = None, - index: AxesData | None = None, + index: AxesData[Any] | None = None, dtype: Dtype | None = None, name: Hashable = None, copy: bool | None = None, @@ -562,9 +562,15 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): def __array_ufunc__( self, ufunc: Callable[..., Any], method: _str, *inputs: Any, **kwargs: Any ) -> Any: ... - def __array__( # ty: ignore[invalid-method-override] - self, dtype: _str | np.dtype = ..., copy: bool | None = ... - ) -> np_1darray: ... + if sys.version_info >= (3, 11): + def __array__( # ty: ignore[invalid-method-override] + self, dtype: _str | np.dtype = ..., copy: bool | None = ... + ) -> np_1darray: ... + else: + def __array__( # ty: ignore[invalid-method-override] + self, dtype: _str | np.dtype[Any] = ..., copy: bool | None = ... + ) -> np_1darray: ... + @final def __getattr__(self, name: _str) -> S1: ... @@ -773,10 +779,10 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): def items(self) -> Iterator[tuple[Hashable, S1]]: ... def keys(self) -> Index: ... @overload - def to_dict(self, *, into: type[dict] = ...) -> dict[Any, S1]: ... + def to_dict(self, *, into: type[dict[Any, Any]] = ...) -> dict[Hashable, S1]: ... @overload def to_dict( - self, *, into: type[MutableMapping] | MutableMapping[Any, Any] + self, *, into: type[MutableMapping[Any, Any]] | MutableMapping[Any, Any] ) -> MutableMapping[Hashable, S1]: ... def to_frame(self, name: object | None = ...) -> DataFrame: ... @overload @@ -837,7 +843,7 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): @overload def groupby( self, - by: MultiIndex | GroupByObjectNonScalar, + by: MultiIndex | GroupByObjectNonScalar[Any], level: IndexLabel | None = ..., as_index: _bool = ..., sort: _bool = ..., @@ -964,7 +970,7 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): self: Series[BooleanDtype], periods: int = ... ) -> Series[BooleanDtype]: ... @overload - def diff(self: Series[Interval], periods: int = ...) -> Never: ... + def diff(self: Series[Interval[_OrderableT]], periods: int = ...) -> Never: ... @overload def diff( self: SupportsGetItem[Scalar, SupportsSelfSub[S2]], periods: int = ... @@ -1099,7 +1105,7 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): def swaplevel( self, i: Level = -2, j: Level = -1, copy: _bool = True ) -> Series[S1]: ... - def reorder_levels(self, order: list) -> Series[S1]: ... + def reorder_levels(self, order: Sequence[int | np.integer]) -> Series[S1]: ... def explode(self, ignore_index: _bool = ...) -> Series[S1]: ... def unstack( self, @@ -1282,20 +1288,20 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): @overload def replace( self, - to_replace: ReplaceValue = ..., - value: ReplaceValue = ..., + to_replace: ReplaceValue[Any, Any] = ..., + value: ReplaceValue[Any, Any] = ..., *, - regex: ReplaceValue = ..., + regex: ReplaceValue[Any, Any] = ..., inplace: Literal[True], # TODO: pandas-dev/pandas#63195 return Self after Pandas 3.0 ) -> None: ... @overload def replace( self, - to_replace: ReplaceValue = ..., - value: ReplaceValue = ..., + to_replace: ReplaceValue[Any, Any] = ..., + value: ReplaceValue[Any, Any] = ..., *, - regex: ReplaceValue = ..., + regex: ReplaceValue[Any, Any] = ..., inplace: Literal[False] = False, ) -> Series[S1]: ... def shift( @@ -4658,7 +4664,7 @@ class Series(IndexOpsMixin[S1], ElementOpsMixin[S1], NDFrame): ) -> Self: ... def set_axis( self, - labels: AxesData, + labels: AxesData[Any], *, axis: Axis = 0, copy: _bool | _NoDefaultDoNotUse = ..., diff --git a/pandas-stubs/io/clipboards.pyi b/pandas-stubs/io/clipboards.pyi index 917b3761b..707d00443 100644 --- a/pandas-stubs/io/clipboards.pyi +++ b/pandas-stubs/io/clipboards.pyi @@ -33,9 +33,9 @@ def read_clipboard( dtype_backend: DtypeBackend | _NoDefaultDoNotUse = ..., delimiter: str | None = ..., header: int | Sequence[int] | Literal["infer"] | None = ..., - names: ListLikeHashable | None = ..., + names: ListLikeHashable[Any] | None = ..., index_col: int | str | Sequence[str | int] | Literal[False] | None = ..., - usecols: UsecolsArgType = ..., + usecols: UsecolsArgType[Any] = ..., dtype: DtypeArg | defaultdict[Any, Any] | None = ..., engine: CSVEngine | None = ..., converters: dict[int | str, Callable[[str], Any]] = ..., @@ -92,9 +92,9 @@ def read_clipboard( dtype_backend: DtypeBackend | _NoDefaultDoNotUse = ..., delimiter: str | None = ..., header: int | Sequence[int] | Literal["infer"] | None = ..., - names: ListLikeHashable | None = ..., + names: ListLikeHashable[Any] | None = ..., index_col: int | str | Sequence[str | int] | Literal[False] | None = ..., - usecols: UsecolsArgType = ..., + usecols: UsecolsArgType[Any] = ..., dtype: DtypeArg | defaultdict[Any, Any] | None = ..., engine: CSVEngine | None = ..., converters: dict[int | str, Callable[[str], Any]] = ..., @@ -151,9 +151,9 @@ def read_clipboard( dtype_backend: DtypeBackend | _NoDefaultDoNotUse = ..., delimiter: str | None = ..., header: int | Sequence[int] | Literal["infer"] | None = ..., - names: ListLikeHashable | None = ..., + names: ListLikeHashable[Any] | None = ..., index_col: int | str | Sequence[str | int] | Literal[False] | None = ..., - usecols: UsecolsArgType = ..., + usecols: UsecolsArgType[Any] = ..., dtype: DtypeArg | defaultdict[Any, Any] | None = ..., engine: CSVEngine | None = ..., converters: dict[int | str, Callable[[str], Any]] = ..., diff --git a/pandas-stubs/io/excel/_base.pyi b/pandas-stubs/io/excel/_base.pyi index 9e772560c..d4d5b097f 100644 --- a/pandas-stubs/io/excel/_base.pyi +++ b/pandas-stubs/io/excel/_base.pyi @@ -49,9 +49,9 @@ def read_excel( sheet_name: list[IntStrT], *, header: int | Sequence[int] | None = ..., - names: ListLikeHashable | None = ..., + names: ListLikeHashable[Any] | None = ..., index_col: int | Sequence[int] | str | None = ..., - usecols: str | UsecolsArgType = ..., + usecols: str | UsecolsArgType[Any] = ..., dtype: str | Dtype | Mapping[str, str | Dtype] | None = ..., engine: ExcelReadEngine | None = ..., converters: Mapping[int | str, Callable[[Any], Any]] | None = ..., @@ -92,9 +92,9 @@ def read_excel( sheet_name: None, *, header: int | Sequence[int] | None = ..., - names: ListLikeHashable | None = ..., + names: ListLikeHashable[Any] | None = ..., index_col: int | Sequence[int] | str | None = ..., - usecols: str | UsecolsArgType = ..., + usecols: str | UsecolsArgType[Any] = ..., dtype: str | Dtype | Mapping[str, str | Dtype] | None = ..., engine: ExcelReadEngine | None = ..., converters: Mapping[int | str, Callable[[Any], Any]] | None = ..., @@ -136,9 +136,9 @@ def read_excel( # type: ignore[overload-cannot-match] sheet_name: list[int | str], *, header: int | Sequence[int] | None = ..., - names: ListLikeHashable | None = ..., + names: ListLikeHashable[Any] | None = ..., index_col: int | Sequence[int] | str | None = ..., - usecols: str | UsecolsArgType = ..., + usecols: str | UsecolsArgType[Any] = ..., dtype: str | Dtype | Mapping[str, str | Dtype] | None = ..., engine: ExcelReadEngine | None = ..., converters: Mapping[int | str, Callable[[Any], Any]] | None = ..., @@ -179,9 +179,9 @@ def read_excel( sheet_name: int | str = ..., *, header: int | Sequence[int] | None = ..., - names: ListLikeHashable | None = ..., + names: ListLikeHashable[Any] | None = ..., index_col: int | Sequence[int] | str | None = ..., - usecols: str | UsecolsArgType = ..., + usecols: str | UsecolsArgType[Any] = ..., dtype: str | Dtype | Mapping[str, str | Dtype] | None = ..., engine: ExcelReadEngine | None = ..., converters: Mapping[int | str, Callable[[Any], Any]] | None = ..., @@ -261,9 +261,9 @@ class ExcelFile: self, sheet_name: list[int | str] | None, header: int | Sequence[int] | None = ..., - names: ListLikeHashable | None = ..., + names: ListLikeHashable[Any] | None = ..., index_col: int | Sequence[int] | None = ..., - usecols: str | UsecolsArgType = ..., + usecols: str | UsecolsArgType[Any] = ..., converters: dict[int | str, Callable[[Any], Any]] | None = ..., true_values: Iterable[Hashable] | None = ..., false_values: Iterable[Hashable] | None = ..., @@ -289,9 +289,9 @@ class ExcelFile: self, sheet_name: int | str, header: int | Sequence[int] | None = ..., - names: ListLikeHashable | None = ..., + names: ListLikeHashable[Any] | None = ..., index_col: int | Sequence[int] | None = ..., - usecols: str | UsecolsArgType = ..., + usecols: str | UsecolsArgType[Any] = ..., converters: dict[int | str, Callable[[Any], Any]] | None = ..., true_values: Iterable[Hashable] | None = ..., false_values: Iterable[Hashable] | None = ..., diff --git a/pandas-stubs/io/html.pyi b/pandas-stubs/io/html.pyi index 091475b26..4a43aa45d 100644 --- a/pandas-stubs/io/html.pyi +++ b/pandas-stubs/io/html.pyi @@ -29,7 +29,7 @@ from pandas._typing import ( def read_html( io: FilePath | ReadBuffer[str], *, - match: str | Pattern = ..., + match: str | Pattern[str] = ..., flavor: HTMLFlavors | Sequence[HTMLFlavors] | None = ..., header: int | Sequence[int] | None = ..., index_col: int | Sequence[int] | list[HashableT1] | None = ..., diff --git a/pandas-stubs/io/json/_json.pyi b/pandas-stubs/io/json/_json.pyi index aabebb978..dc1f2ac0c 100644 --- a/pandas-stubs/io/json/_json.pyi +++ b/pandas-stubs/io/json/_json.pyi @@ -2,6 +2,7 @@ from collections import abc from collections.abc import Mapping from types import TracebackType from typing import ( + Any, Generic, Literal, overload, @@ -226,7 +227,7 @@ def read_json( engine: Literal["pyarrow"], ) -> DataFrame: ... -class JsonReader(abc.Iterator, Generic[NDFrameT]): +class JsonReader(abc.Iterator[Any], Generic[NDFrameT]): def read(self) -> NDFrameT: ... def close(self) -> None: ... def __iter__(self) -> JsonReader[NDFrameT]: ... diff --git a/pandas-stubs/io/parsers/readers.pyi b/pandas-stubs/io/parsers/readers.pyi index e414b4ca3..660a7f949 100644 --- a/pandas-stubs/io/parsers/readers.pyi +++ b/pandas-stubs/io/parsers/readers.pyi @@ -41,7 +41,7 @@ def read_csv( sep: str | None = ..., delimiter: str | None = None, header: int | Sequence[int] | Literal["infer"] | None = "infer", - names: ListLikeHashable | None = ..., + names: ListLikeHashable[Any] | None = ..., index_col: int | str | Sequence[str | int] | Literal[False] | None = None, usecols: UsecolsArgType[HashableT] = None, dtype: DtypeArg | defaultdict[Any, Any] | None = None, @@ -104,7 +104,7 @@ def read_csv( sep: str | None = ..., delimiter: str | None = None, header: int | Sequence[int] | Literal["infer"] | None = "infer", - names: ListLikeHashable | None = ..., + names: ListLikeHashable[Any] | None = ..., index_col: int | str | Sequence[str | int] | Literal[False] | None = None, usecols: UsecolsArgType[HashableT] = None, dtype: DtypeArg | defaultdict[Any, Any] | None = None, @@ -167,7 +167,7 @@ def read_csv( sep: str | None = ..., delimiter: str | None = ..., header: int | Sequence[int] | Literal["infer"] | None = ..., - names: ListLikeHashable | None = ..., + names: ListLikeHashable[Any] | None = ..., index_col: int | str | Sequence[str | int] | Literal[False] | None = ..., usecols: UsecolsArgType[HashableT] = ..., dtype: DtypeArg | defaultdict[Any, Any] | None = ..., @@ -230,7 +230,7 @@ def read_table( sep: str | None = ..., delimiter: str | None = None, header: int | Sequence[int] | Literal["infer"] | None = "infer", - names: ListLikeHashable | None = ..., + names: ListLikeHashable[Any] | None = ..., index_col: int | str | Sequence[str | int] | Literal[False] | None = None, usecols: UsecolsArgType[HashableT] = None, dtype: DtypeArg | defaultdict[Any, Any] | None = None, @@ -293,7 +293,7 @@ def read_table( sep: str | None = ..., delimiter: str | None = None, header: int | Sequence[int] | Literal["infer"] | None = "infer", - names: ListLikeHashable | None = ..., + names: ListLikeHashable[Any] | None = ..., index_col: int | str | Sequence[str | int] | Literal[False] | None = None, usecols: UsecolsArgType[HashableT] = None, dtype: DtypeArg | defaultdict[Any, Any] | None = None, @@ -356,7 +356,7 @@ def read_table( sep: str | None = ..., delimiter: str | None = None, header: int | Sequence[int] | Literal["infer"] | None = "infer", - names: ListLikeHashable | None = ..., + names: ListLikeHashable[Any] | None = ..., index_col: int | str | Sequence[str | int] | Literal[False] | None = None, usecols: UsecolsArgType[HashableT] = None, dtype: DtypeArg | defaultdict[Any, Any] | None = None, @@ -452,7 +452,7 @@ def read_fwf( **kwds: Any, ) -> DataFrame: ... -class TextFileReader(abc.Iterator): +class TextFileReader(abc.Iterator[Any]): engine: CSVEngine orig_options: Mapping[str, Any] chunksize: int | None diff --git a/pandas-stubs/io/sql.pyi b/pandas-stubs/io/sql.pyi index 4d92623de..c3f7a4333 100644 --- a/pandas-stubs/io/sql.pyi +++ b/pandas-stubs/io/sql.pyi @@ -33,8 +33,8 @@ _SQLStatement: TypeAlias = ( str | sqlalchemy.sql.expression.Selectable | sqlalchemy.sql.expression.TextClause - | sqlalchemy.sql.Select - | FromStatement + | sqlalchemy.sql.Select[Any] + | FromStatement[Any] | sqlalchemy.sql.expression.UpdateBase ) @@ -155,7 +155,7 @@ class PandasSQL: dtype: DtypeArg | None = None, method: ( Literal["multi"] - | Callable[[SQLTable, Any, list[str], Iterable], int | None] + | Callable[[SQLTable, Any, list[str], Iterable[Any]], int | None] | None ) = None, engine: str = "auto", @@ -189,7 +189,7 @@ class SQLTable: def exists(self) -> bool: ... def sql_schema(self) -> str: ... def create(self) -> None: ... - def insert_data(self) -> tuple[list[str], list[npt.NDArray]]: ... + def insert_data(self) -> tuple[list[str], list[npt.NDArray[Any]]]: ... def insert( self, chunksize: int | None = ..., method: str | None = ... ) -> int | None: ... diff --git a/pandas-stubs/io/stata.pyi b/pandas-stubs/io/stata.pyi index ce50b8083..91f47b858 100644 --- a/pandas-stubs/io/stata.pyi +++ b/pandas-stubs/io/stata.pyi @@ -4,6 +4,7 @@ import datetime from io import BytesIO from types import TracebackType from typing import ( + Any, Literal, overload, ) @@ -76,7 +77,7 @@ def read_stata( class StataParser: def __init__(self) -> None: ... -class StataReader(StataParser, abc.Iterator): +class StataReader(StataParser, abc.Iterator[Any]): col_sizes: list[int] = ... path_or_buf: BytesIO = ... def __init__( diff --git a/pandas-stubs/io/xml.pyi b/pandas-stubs/io/xml.pyi index d76408e75..c11f20cfc 100644 --- a/pandas-stubs/io/xml.pyi +++ b/pandas-stubs/io/xml.pyi @@ -1,4 +1,5 @@ from collections.abc import Sequence +from typing import Any from pandas.core.frame import DataFrame @@ -25,7 +26,7 @@ def read_xml( names: Sequence[str] | None = ..., dtype: DtypeArg | None = ..., converters: ConvertersArg | None = ..., - parse_dates: ParseDatesArg | None = ..., + parse_dates: ParseDatesArg[Any, Any] | None = ..., # encoding can not be None for lxml and StringIO input encoding: str | None = ..., parser: XMLParsers = ..., diff --git a/pandas-stubs/plotting/_core.pyi b/pandas-stubs/plotting/_core.pyi index 527224442..633512fe0 100644 --- a/pandas-stubs/plotting/_core.pyi +++ b/pandas-stubs/plotting/_core.pyi @@ -45,7 +45,7 @@ _PlotAccessorColor: TypeAlias = str | list[_SingleColor] | dict[HashableT, _Sing @overload def boxplot( data: DataFrame, - column: Hashable | ListLikeHashable, + column: Hashable | ListLikeHashable[Any], by: None = None, ax: Axes | None = None, fontsize: float | str | None = None, @@ -61,7 +61,7 @@ def boxplot( @overload def boxplot( data: DataFrame, - column: Hashable | ListLikeHashable, + column: Hashable | ListLikeHashable[Any], by: None = None, ax: Axes | None = None, fontsize: float | str | None = None, @@ -77,7 +77,7 @@ def boxplot( @overload def boxplot( data: DataFrame, - column: Hashable | ListLikeHashable, + column: Hashable | ListLikeHashable[Any], by: None = None, ax: Axes | None = None, fontsize: float | str | None = None, @@ -93,8 +93,8 @@ def boxplot( @overload def boxplot( data: DataFrame, - column: Hashable | ListLikeHashable, - by: Hashable | ListLikeHashable, + column: Hashable | ListLikeHashable[Any], + by: Hashable | ListLikeHashable[Any], ax: Axes | None = None, fontsize: float | str | None = None, rot: float = 0, @@ -109,8 +109,8 @@ def boxplot( @overload def boxplot( data: DataFrame, - column: Hashable | ListLikeHashable, - by: Hashable | ListLikeHashable, + column: Hashable | ListLikeHashable[Any], + by: Hashable | ListLikeHashable[Any], ax: Axes | None = None, fontsize: float | str | None = None, rot: float = 0, @@ -282,7 +282,7 @@ class PlotAccessor: self, x: Hashable = ..., y: Hashable = ..., - color: _PlotAccessorColor = ..., + color: _PlotAccessorColor[Any] = ..., *, subplots: Literal[False] | None = ..., **kwargs: Any, @@ -292,7 +292,7 @@ class PlotAccessor: self, x: Hashable = ..., y: Hashable = ..., - color: _PlotAccessorColor = ..., + color: _PlotAccessorColor[Any] = ..., *, subplots: Literal[True], **kwargs: Any, @@ -302,7 +302,7 @@ class PlotAccessor: self, x: Hashable = ..., y: Hashable = ..., - color: _PlotAccessorColor = ..., + color: _PlotAccessorColor[Any] = ..., *, subplots: Literal[False] | None = ..., **kwargs: Any, @@ -312,7 +312,7 @@ class PlotAccessor: self, x: Hashable = ..., y: Hashable = ..., - color: _PlotAccessorColor = ..., + color: _PlotAccessorColor[Any] = ..., *, subplots: Literal[True], **kwargs: Any, @@ -322,7 +322,7 @@ class PlotAccessor: self, x: Hashable = ..., y: Hashable = ..., - color: _PlotAccessorColor = ..., + color: _PlotAccessorColor[Any] = ..., subplots: Literal[False] | None = ..., **kwargs: Any, ) -> Axes: ... @@ -331,7 +331,7 @@ class PlotAccessor: self, x: Hashable = ..., y: Hashable = ..., - color: _PlotAccessorColor = ..., + color: _PlotAccessorColor[Any] = ..., *, subplots: Literal[True], **kwargs: Any, diff --git a/pyproject.toml b/pyproject.toml index 35fd38a6d..b8d837a78 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -314,7 +314,6 @@ include = ["tests", "pandas-stubs"] enableTypeIgnoreComments = false # use pyright-specific ignores # disable subset of strict reportMissingParameterType = false -reportMissingTypeArgument = false reportUnnecessaryTypeIgnoreComment = true reportUnknownArgumentType = false reportUnknownLambdaType = false diff --git a/tests/__init__.py b/tests/__init__.py index f11a46a34..1ac265c2b 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -8,6 +8,7 @@ import sys from typing import ( TYPE_CHECKING, + Any, Final, Literal, get_args, @@ -160,7 +161,7 @@ def pytest_warns_bounded( upper: str | None = None, version_str: str | None = None, upper_exception: type[Exception] | None = None, -) -> AbstractContextManager: +) -> AbstractContextManager[Any]: """ Version conditional pytest.warns context manager diff --git a/tests/extension/decimal/array.py b/tests/extension/decimal/array.py index 26cccd2f5..dfcff1ecb 100644 --- a/tests/extension/decimal/array.py +++ b/tests/extension/decimal/array.py @@ -230,8 +230,15 @@ def take( def copy(self) -> DecimalArray: return type(self)(self._data.copy(), dtype=self.dtype) - @overload - def astype(self, dtype: np.dtype, copy: bool = True) -> np_1darray: ... + if sys.version_info >= (3, 11): + + @overload + def astype(self, dtype: np.dtype, copy: bool = True) -> np_1darray: ... + + else: + + @overload + def astype(self, dtype: np.dtype[Any], copy: bool = True) -> np_1darray: ... @overload def astype(self, dtype: ExtensionDtype, copy: bool = True) -> ExtensionArray: ... @overload diff --git a/tests/frame/test_frame.py b/tests/frame/test_frame.py index 67e5b0445..c72148337 100644 --- a/tests/frame/test_frame.py +++ b/tests/frame/test_frame.py @@ -2998,19 +2998,42 @@ def test_to_xarray() -> None: def test_to_records() -> None: df = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]}) - check(assert_type(df.to_records(False, "int8"), np.recarray), np.recarray) - check( - assert_type(df.to_records(False, index_dtypes=np.int8), np.recarray), - np.recarray, - ) - check( - assert_type( - df.to_records(False, {"col1": np.int8, "col2": np.int16}), np.recarray - ), - np.recarray, - ) dtypes = {"col1": np.int8, "col2": np.int16} - check(assert_type(df.to_records(False, dtypes), np.recarray), np.recarray) + if sys.version_info >= (3, 11): + check(assert_type(df.to_records(False, "int8"), np.recarray), np.recarray) + check( + assert_type(df.to_records(False, index_dtypes=np.int8), np.recarray), + np.recarray, + ) + check( + assert_type( + df.to_records(False, {"col1": np.int8, "col2": np.int16}), np.recarray + ), + np.recarray, + ) + check(assert_type(df.to_records(False, dtypes), np.recarray), np.recarray) + else: + check( + assert_type(df.to_records(False, "int8"), np.recarray[Any, Any]), + np.recarray, + ) + check( + assert_type( + df.to_records(False, index_dtypes=np.int8), np.recarray[Any, Any] + ), + np.recarray, + ) + check( + assert_type( + df.to_records(False, {"col1": np.int8, "col2": np.int16}), + np.recarray[Any, Any], + ), + np.recarray, + ) + check( + assert_type(df.to_records(False, dtypes), np.recarray[Any, Any]), + np.recarray, + ) def test_to_dict_simple() -> None: @@ -3021,14 +3044,16 @@ def test_to_dict_simple() -> None: check(assert_type(data.to_dict("dict"), dict[Hashable, Any]), dict) check(assert_type(data.to_dict("list"), dict[Hashable, Any]), dict) check(assert_type(data.to_dict("series"), dict[Hashable, Any]), dict) - check(assert_type(data.to_dict("split"), dict[str, list]), dict, str) + check(assert_type(data.to_dict("split"), dict[str, list[Any]]), dict, str) # orient param accepting "tight" added in 1.4.0 https://pandas.pydata.org/docs/whatsnew/v1.4.0.html - check(assert_type(data.to_dict("tight"), dict[str, list]), dict, str) + check(assert_type(data.to_dict("tight"), dict[str, list[Any]]), dict, str) if TYPE_CHECKING_INVALID_USAGE: - def test(mapping: Mapping) -> None: # pyright: ignore[reportUnusedFunction] + def test( # pyright: ignore[reportUnusedFunction] + mapping: Mapping[Any, Any], + ) -> None: data.to_dict(into=mapping) # type: ignore[call-overload] # pyright: ignore[reportArgumentType,reportCallIssue] def _1() -> None: # pyright: ignore[reportUnusedFunction] @@ -3075,7 +3100,7 @@ def test_to_dict_into_defaultdict() -> None: defaultdict, ) check( - assert_type(data.to_dict("tight", into=target), MutableMapping[str, list]), + assert_type(data.to_dict("tight", into=target), MutableMapping[str, list[Any]]), defaultdict, str, ) @@ -3093,7 +3118,11 @@ def test_to_dict_into_ordered_dict() -> None: data = pd.DataFrame({("str", "rts"): [[1, 2, 4], [2, 3], [3]]}) - check(assert_type(data.to_dict(into=OrderedDict), OrderedDict), OrderedDict, tuple) + check( + assert_type(data.to_dict(into=OrderedDict), OrderedDict[Any, Any]), + OrderedDict, + tuple, + ) check( assert_type( data.to_dict("index", into=OrderedDict), @@ -3102,12 +3131,16 @@ def test_to_dict_into_ordered_dict() -> None: OrderedDict, ) check( - assert_type(data.to_dict("tight", into=OrderedDict), MutableMapping[str, list]), + assert_type( + data.to_dict("tight", into=OrderedDict), MutableMapping[str, list[Any]] + ), OrderedDict, str, ) check( - assert_type(data.to_dict("records", into=OrderedDict), list[OrderedDict]), + assert_type( + data.to_dict("records", into=OrderedDict), list[OrderedDict[Any, Any]] + ), list, OrderedDict, ) @@ -3446,16 +3479,24 @@ def test_to_dict_index() -> None: dict, ) check( - assert_type(df.to_dict(orient="split", index=True), dict[str, list]), dict, str + assert_type(df.to_dict(orient="split", index=True), dict[str, list[Any]]), + dict, + str, ) check( - assert_type(df.to_dict(orient="tight", index=True), dict[str, list]), dict, str + assert_type(df.to_dict(orient="tight", index=True), dict[str, list[Any]]), + dict, + str, ) check( - assert_type(df.to_dict(orient="tight", index=False), dict[str, list]), dict, str + assert_type(df.to_dict(orient="tight", index=False), dict[str, list[Any]]), + dict, + str, ) check( - assert_type(df.to_dict(orient="split", index=False), dict[str, list]), dict, str + assert_type(df.to_dict(orient="split", index=False), dict[str, list[Any]]), + dict, + str, ) if TYPE_CHECKING_INVALID_USAGE: _0 = df.to_dict(orient="records", index=False) # type: ignore[call-overload] # pyright: ignore[reportArgumentType,reportCallIssue] diff --git a/tests/frame/test_groupby.py b/tests/frame/test_groupby.py index 20c2f013f..2f39e870f 100644 --- a/tests/frame/test_groupby.py +++ b/tests/frame/test_groupby.py @@ -531,7 +531,7 @@ def sum_mean(x: pd.DataFrame) -> float: ): check(assert_type(df.groupby("col1").apply(lfunc), pd.Series), pd.Series) - def sum_to_list(x: pd.DataFrame) -> list: + def sum_to_list(x: pd.DataFrame) -> list[Any]: return x.sum().tolist() with pytest_warns_bounded( diff --git a/tests/indexes/test_indexes.py b/tests/indexes/test_indexes.py index 2d764df46..ab1a66a3a 100644 --- a/tests/indexes/test_indexes.py +++ b/tests/indexes/test_indexes.py @@ -1674,9 +1674,15 @@ def test_index_view() -> None: # - pyright: ndarray[tuple[Any, ...], dtype[Any]] check(assert_type(ind.view(np.ndarray), np.ndarray), np.ndarray) # type: ignore[assert-type] else: - check(assert_type(ind.view(np.ndarray), np.ndarray), np.ndarray) + check(assert_type(ind.view(np.ndarray), np.ndarray[Any, Any]), np.ndarray) - class MyArray(np.ndarray): ... + if sys.version_info >= (3, 11): + + class MyArray(np.ndarray): ... + + else: + + class MyArray(np.ndarray[Any, Any]): ... check(assert_type(ind.view(MyArray), MyArray), MyArray) diff --git a/tests/series/test_properties.py b/tests/series/test_properties.py index 844336ab9..526fadba3 100644 --- a/tests/series/test_properties.py +++ b/tests/series/test_properties.py @@ -1,4 +1,7 @@ -from typing import TYPE_CHECKING +from typing import ( + TYPE_CHECKING, +) +from typing import Any # noqa: F401 import numpy as np from pandas.core.arrays import DatetimeArray @@ -44,7 +47,7 @@ def test_property_dt() -> None: check( assert_type( period_range(start="2022-06-01", periods=10).to_series().dt, - PeriodProperties, + "PeriodProperties[Any]", ), PeriodProperties, ) diff --git a/tests/series/test_series.py b/tests/series/test_series.py index 96d3e411c..bfd4028a7 100644 --- a/tests/series/test_series.py +++ b/tests/series/test_series.py @@ -838,7 +838,7 @@ def makeseries(x: float) -> pd.Series: def retseries(x: float) -> float: return x - check(assert_type(s.apply(retseries).tolist(), list), list) + check(assert_type(s.apply(retseries).tolist(), list[Any]), list) def retlist(x: float) -> list[float]: return [x] @@ -1780,7 +1780,7 @@ def test_types_to_list() -> None: def test_types_to_dict() -> None: s = pd.Series(["a", "b", "c"], dtype=str) - assert_type(s.to_dict(), dict[Any, str]) + assert_type(s.to_dict(), dict[Hashable, str]) def test_categorical_codes() -> None: @@ -2182,7 +2182,7 @@ def test_change_to_dict_return_type() -> None: value = ["a", "b", "c"] df = pd.DataFrame(zip(id, value), columns=["id", "value"]) fd = df.set_index("id")["value"].to_dict() - check(assert_type(fd, dict[Any, Any]), dict) + check(assert_type(fd, dict[Hashable, Any]), dict) ASTYPE_BOOL_ARGS: list[tuple[BooleanDtypeArg, type]] = [ diff --git a/tests/test_api_typing.py b/tests/test_api_typing.py index 5b01be922..560274ba3 100644 --- a/tests/test_api_typing.py +++ b/tests/test_api_typing.py @@ -1,6 +1,10 @@ """Test module for classes in pandas.api.typing.""" -from typing import TypeAlias +from typing import ( + TYPE_CHECKING, + Any, + TypeAlias, +) import numpy as np import pandas as pd @@ -35,18 +39,25 @@ ensure_clean, ) -ResamplerGroupBy: TypeAlias = ( - DatetimeIndexResamplerGroupby - | PeriodIndexResamplerGroupby - | TimedeltaIndexResamplerGroupby -) +if TYPE_CHECKING: + ResamplerGroupBy: TypeAlias = ( + DatetimeIndexResamplerGroupby[Any] + | PeriodIndexResamplerGroupby[Any] + | TimedeltaIndexResamplerGroupby[Any] + ) +else: + ResamplerGroupBy: TypeAlias = ( + DatetimeIndexResamplerGroupby + | PeriodIndexResamplerGroupby + | TimedeltaIndexResamplerGroupby + ) def test_dataframegroupby() -> None: df = pd.DataFrame({"a": [1, 2, 3]}) group = df.groupby("a") - def f1(gb: DataFrameGroupBy) -> None: + def f1(gb: "DataFrameGroupBy[Any, Any]") -> None: check(gb, DataFrameGroupBy) f1(group) @@ -55,7 +66,7 @@ def f1(gb: DataFrameGroupBy) -> None: def test_seriesgroupby() -> None: sr = pd.Series([1, 2, 3], index=pd.Index(["a", "b", "a"])) - def f1(gb: SeriesGroupBy) -> None: + def f1(gb: "SeriesGroupBy[Any, Any]") -> None: check(gb, SeriesGroupBy) f1(sr.groupby(level=0)) @@ -113,7 +124,7 @@ def test_nattype() -> None: def test_expanding() -> None: df = pd.DataFrame({"B": [0, 1, 2, np.nan, 4]}) - def f1(gb: Expanding) -> None: + def f1(gb: "Expanding[Any]") -> None: check(gb, Expanding) f1(df.expanding()) @@ -122,7 +133,7 @@ def f1(gb: Expanding) -> None: def test_expanding_groubpy() -> None: df = pd.DataFrame({"B": [0, 1, 2, np.nan, 4]}) - def f1(gb: ExpandingGroupby) -> None: + def f1(gb: "ExpandingGroupby[Any]") -> None: check(gb, ExpandingGroupby) f1(df.groupby("B").expanding()) @@ -131,7 +142,7 @@ def f1(gb: ExpandingGroupby) -> None: def test_ewm() -> None: df = pd.DataFrame({"B": [0, 1, 2, np.nan, 4]}) - def f1(gb: ExponentialMovingWindow) -> None: + def f1(gb: "ExponentialMovingWindow[Any]") -> None: check(gb, ExponentialMovingWindow) f1(df.ewm(2)) @@ -140,7 +151,7 @@ def f1(gb: ExponentialMovingWindow) -> None: def test_ewm_groubpy() -> None: df = pd.DataFrame({"B": [0, 1, 2, np.nan, 4]}) - def f1(gb: ExponentialMovingWindowGroupby) -> None: + def f1(gb: "ExponentialMovingWindowGroupby[Any]") -> None: check(gb, ExponentialMovingWindowGroupby) f1(df.groupby("B").ewm(2)) @@ -149,7 +160,7 @@ def f1(gb: ExponentialMovingWindowGroupby) -> None: def test_json_reader() -> None: df = pd.DataFrame({"B": [0, 1, 2, np.nan, 4]}) - def f1(gb: JsonReader) -> None: + def f1(gb: JsonReader[Any]) -> None: check(gb, JsonReader) with ensure_clean() as path: @@ -162,7 +173,7 @@ def f1(gb: JsonReader) -> None: def test_resampler() -> None: s = pd.Series([1, 2, 3, 4, 5], index=pd.date_range("20130101", periods=5, freq="s")) - def f1(gb: Resampler) -> None: + def f1(gb: "Resampler[Any]") -> None: check(gb, Resampler) f1(s.resample("3min")) @@ -171,7 +182,7 @@ def f1(gb: Resampler) -> None: def test_rolling() -> None: df = pd.DataFrame({"B": [0, 1, 2, np.nan, 4]}) - def f1(gb: Rolling) -> None: + def f1(gb: "Rolling[Any]") -> None: check(gb, Rolling) f1(df.rolling(2)) @@ -180,7 +191,7 @@ def f1(gb: Rolling) -> None: def test_rolling_groupby() -> None: df = pd.DataFrame({"B": [0, 1, 2, np.nan, 4]}) - def f1(gb: RollingGroupby) -> None: + def f1(gb: "RollingGroupby[Any]") -> None: check(gb, RollingGroupby) f1(df.groupby("B").rolling(2)) @@ -198,7 +209,7 @@ def f1(gb: TimeGrouper) -> None: def test_window() -> None: ser = pd.Series([0, 1, 5, 2, 8]) - def f1(gb: Window) -> None: + def f1(gb: Window[Any]) -> None: check(gb, Window) f1(ser.rolling(2, win_type="gaussian")) diff --git a/tests/test_extension.py b/tests/test_extension.py index c2e0c52f2..15acdf328 100644 --- a/tests/test_extension.py +++ b/tests/test_extension.py @@ -1,4 +1,5 @@ import decimal +from typing import Any import numpy as np import pandas as pd @@ -29,9 +30,9 @@ def test_tolist() -> None: s1 = pd.Series(data1) # python/mypy#19952: mypy believes ExtensionArray and its subclasses have a # conflict and gives Any for s.array - check(assert_type(s.array.tolist(), list), list) # type: ignore[assert-type] - check(assert_type(s1.array.tolist(), list), list) - check(assert_type(pd.array([1, 2, 3]).tolist(), list), list) + check(assert_type(s.array.tolist(), list[Any]), list) # type: ignore[assert-type] + check(assert_type(s1.array.tolist(), list[Any]), list) + check(assert_type(pd.array([1, 2, 3]).tolist(), list[Any]), list) def test_ExtensionArray_reduce_accumulate() -> None: diff --git a/tests/test_interval.py b/tests/test_interval.py index 398bda276..0dc0c3f90 100644 --- a/tests/test_interval.py +++ b/tests/test_interval.py @@ -2,6 +2,7 @@ import numpy as np import pandas as pd +from pandas.core.arrays.interval import IntervalArray from typing_extensions import assert_type from tests import ( @@ -125,6 +126,6 @@ def test_interval_array_contains() -> None: df = pd.DataFrame({"A": range(1, 10)}) obj = pd.Interval(1, 4) ser = pd.Series(obj, index=df.index) - arr = ser.array + arr = check(assert_type(ser.array, IntervalArray), IntervalArray) check(assert_type(arr.contains(df["A"]), "pd.Series[bool]"), pd.Series, np.bool_) check(assert_type(arr.contains(3), np_1darray_bool), np_1darray_bool) diff --git a/tests/test_resampler.py b/tests/test_resampler.py index 3fa7ac15a..ff132f599 100644 --- a/tests/test_resampler.py +++ b/tests/test_resampler.py @@ -2,20 +2,20 @@ Hashable, Iterator, ) -from typing import TypeAlias +from typing import ( + TypeAlias, +) +from typing import Any # noqa: F401 import numpy as np -import pandas as pd -from pandas import ( - DataFrame, - Series, - date_range, -) +from pandas.core.frame import DataFrame from pandas.core.groupby.generic import ( DataFrameGroupBy, SeriesGroupBy, ) +from pandas.core.indexes.datetimes import date_range from pandas.core.resample import DatetimeIndexResampler +from pandas.core.series import Series from typing_extensions import assert_type from tests import ( @@ -141,7 +141,7 @@ def test_asfreq() -> None: def test_getattr() -> None: - check(assert_type(DF.resample("ME").col1, SeriesGroupBy), SeriesGroupBy) + check(assert_type(DF.resample("ME").col1, "SeriesGroupBy[Any, Any]"), SeriesGroupBy) def test_interpolate() -> None: @@ -403,7 +403,7 @@ def f(val: Series) -> Series: def test_aggregate_series_combinations() -> None: def s2series(val: Series) -> Series: - return pd.Series(val) + return Series(val) def s2scalar(val: Series) -> float: return float(val.mean()) @@ -425,7 +425,7 @@ def s2scalar(val: Series) -> float: def test_aggregate_frame_combinations() -> None: def df2frame(val: DataFrame) -> DataFrame: - return pd.DataFrame(val) + return DataFrame(val) def df2series(val: DataFrame) -> Series: return val.mean() @@ -466,8 +466,10 @@ def df2scalar(val: DataFrame) -> float: def test_getitem() -> None: - check(assert_type(DF.resample("ME")["col1"], SeriesGroupBy), SeriesGroupBy) check( - assert_type(DF.resample("ME")[["col1", "col2"]], DataFrameGroupBy), + assert_type(DF.resample("ME")["col1"], "SeriesGroupBy[Any, Any]"), SeriesGroupBy + ) + check( + assert_type(DF.resample("ME")[["col1", "col2"]], "DataFrameGroupBy[Any, Any]"), DataFrameGroupBy, )