Skip to content

Commit 49d3713

Browse files
authored
TYP: fix reportInvalidTypeVarUse from pyright (#42367)
1 parent 8276a56 commit 49d3713

20 files changed

+94
-75
lines changed

pandas/_libs/tslibs/dtypes.pyi

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ class PeriodDtypeBase:
99
_dtype_code: int # PeriodDtypeCode
1010

1111
# actually __cinit__
12-
def __new__(self, code: int): ...
12+
def __new__(cls, code: int): ...
1313
def freq_group_code(self) -> int: ...
1414
def date_offset(self) -> BaseOffset: ...
1515
@classmethod

pandas/_testing/_io.py

+11-5
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,13 @@
44
from functools import wraps
55
import gzip
66
from typing import (
7+
TYPE_CHECKING,
78
Any,
89
Callable,
910
)
1011
import zipfile
1112

12-
from pandas._typing import (
13-
FilePathOrBuffer,
14-
FrameOrSeries,
15-
)
13+
from pandas._typing import FilePathOrBuffer
1614
from pandas.compat import (
1715
get_lzma_file,
1816
import_lzma,
@@ -24,6 +22,12 @@
2422

2523
from pandas.io.common import urlopen
2624

25+
if TYPE_CHECKING:
26+
from pandas import (
27+
DataFrame,
28+
Series,
29+
)
30+
2731
_RAISE_NETWORK_ERROR_DEFAULT = False
2832

2933
lzma = import_lzma()
@@ -272,7 +276,9 @@ def can_connect(url, error_classes=None):
272276
# File-IO
273277

274278

275-
def round_trip_pickle(obj: Any, path: FilePathOrBuffer | None = None) -> FrameOrSeries:
279+
def round_trip_pickle(
280+
obj: Any, path: FilePathOrBuffer | None = None
281+
) -> DataFrame | Series:
276282
"""
277283
Pickle an object and then read it again.
278284

pandas/core/apply.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1338,7 +1338,7 @@ def _make_unique_kwarg_list(
13381338

13391339

13401340
def relabel_result(
1341-
result: FrameOrSeries,
1341+
result: DataFrame | Series,
13421342
func: dict[str, list[Callable | str]],
13431343
columns: Iterable[Hashable],
13441344
order: Iterable[int],

pandas/core/arrays/_mixins.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,7 @@ def __repr__(self) -> str:
323323
# ------------------------------------------------------------------------
324324
# __array_function__ methods
325325

326-
def putmask(self: NDArrayBackedExtensionArrayT, mask: np.ndarray, value) -> None:
326+
def putmask(self, mask: np.ndarray, value) -> None:
327327
"""
328328
Analogue to np.putmask(self, mask, value)
329329

pandas/core/arrays/interval.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -934,9 +934,7 @@ def copy(self: IntervalArrayT) -> IntervalArrayT:
934934
def isna(self) -> np.ndarray:
935935
return isna(self._left)
936936

937-
def shift(
938-
self: IntervalArrayT, periods: int = 1, fill_value: object = None
939-
) -> IntervalArray:
937+
def shift(self, periods: int = 1, fill_value: object = None) -> IntervalArray:
940938
if not len(self) or periods == 0:
941939
return self.copy()
942940

pandas/core/generic.py

+8-10
Original file line numberDiff line numberDiff line change
@@ -709,13 +709,11 @@ def set_axis(
709709
...
710710

711711
@overload
712-
def set_axis(
713-
self: FrameOrSeries, labels, axis: Axis, inplace: Literal[True]
714-
) -> None:
712+
def set_axis(self, labels, axis: Axis, inplace: Literal[True]) -> None:
715713
...
716714

717715
@overload
718-
def set_axis(self: FrameOrSeries, labels, *, inplace: Literal[True]) -> None:
716+
def set_axis(self, labels, *, inplace: Literal[True]) -> None:
719717
...
720718

721719
@overload
@@ -2703,10 +2701,12 @@ def to_hdf(
27032701
"""
27042702
from pandas.io import pytables
27052703

2704+
# Argument 3 to "to_hdf" has incompatible type "NDFrame"; expected
2705+
# "Union[DataFrame, Series]" [arg-type]
27062706
pytables.to_hdf(
27072707
path_or_buf,
27082708
key,
2709-
self,
2709+
self, # type: ignore[arg-type]
27102710
mode=mode,
27112711
complevel=complevel,
27122712
complib=complib,
@@ -3850,7 +3850,7 @@ def _slice(self: FrameOrSeries, slobj: slice, axis=0) -> FrameOrSeries:
38503850
return result
38513851

38523852
@final
3853-
def _set_is_copy(self, ref: FrameOrSeries, copy: bool_t = True) -> None:
3853+
def _set_is_copy(self, ref: NDFrame, copy: bool_t = True) -> None:
38543854
if not copy:
38553855
self._is_copy = None
38563856
else:
@@ -11019,13 +11019,11 @@ def ewm(
1101911019
adjust: bool_t = True,
1102011020
ignore_na: bool_t = False,
1102111021
axis: Axis = 0,
11022-
times: str | np.ndarray | FrameOrSeries | None = None,
11022+
times: str | np.ndarray | DataFrame | Series | None = None,
1102311023
method: str = "single",
1102411024
) -> ExponentialMovingWindow:
1102511025
axis = self._get_axis_number(axis)
11026-
# error: Value of type variable "FrameOrSeries" of "ExponentialMovingWindow"
11027-
# cannot be "object"
11028-
return ExponentialMovingWindow( # type: ignore[type-var]
11026+
return ExponentialMovingWindow(
1102911027
self,
1103011028
com=com,
1103111029
span=span,

pandas/core/groupby/generic.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1523,7 +1523,7 @@ def _wrap_agged_manager(self, mgr: Manager2D) -> DataFrame:
15231523
# values converted
15241524
return self._reindex_output(result)._convert(datetime=True)
15251525

1526-
def _iterate_column_groupbys(self, obj: FrameOrSeries):
1526+
def _iterate_column_groupbys(self, obj: DataFrame | Series):
15271527
for i, colname in enumerate(obj.columns):
15281528
yield colname, SeriesGroupBy(
15291529
obj.iloc[:, i],
@@ -1532,7 +1532,7 @@ def _iterate_column_groupbys(self, obj: FrameOrSeries):
15321532
exclusions=self.exclusions,
15331533
)
15341534

1535-
def _apply_to_column_groupbys(self, func, obj: FrameOrSeries) -> DataFrame:
1535+
def _apply_to_column_groupbys(self, func, obj: DataFrame | Series) -> DataFrame:
15361536
from pandas.core.reshape.concat import concat
15371537

15381538
columns = obj.columns

pandas/core/groupby/groupby.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,6 @@ class providing the base-class of operations.
4444
import pandas._libs.groupby as libgroupby
4545
from pandas._typing import (
4646
ArrayLike,
47-
F,
4847
FrameOrSeries,
4948
IndexLabel,
5049
RandomState,
@@ -1373,7 +1372,10 @@ def f(g):
13731372

13741373
@final
13751374
def _python_apply_general(
1376-
self, f: F, data: DataFrame | Series, not_indexed_same: bool | None = None
1375+
self,
1376+
f: Callable,
1377+
data: DataFrame | Series,
1378+
not_indexed_same: bool | None = None,
13771379
) -> DataFrame | Series:
13781380
"""
13791381
Apply function f in python space

pandas/core/groupby/grouper.py

+15-8
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
from __future__ import annotations
66

77
from typing import (
8+
TYPE_CHECKING,
9+
Any,
810
Hashable,
911
final,
1012
)
@@ -47,6 +49,9 @@
4749

4850
from pandas.io.formats.printing import pprint_thing
4951

52+
if TYPE_CHECKING:
53+
from pandas.core.generic import NDFrame
54+
5055

5156
class Grouper:
5257
"""
@@ -299,7 +304,9 @@ def ax(self) -> Index:
299304
raise ValueError("_set_grouper must be called before ax is accessed")
300305
return index
301306

302-
def _get_grouper(self, obj: FrameOrSeries, validate: bool = True):
307+
def _get_grouper(
308+
self, obj: FrameOrSeries, validate: bool = True
309+
) -> tuple[Any, ops.BaseGrouper, FrameOrSeries]:
303310
"""
304311
Parameters
305312
----------
@@ -326,10 +333,12 @@ def _get_grouper(self, obj: FrameOrSeries, validate: bool = True):
326333
dropna=self.dropna,
327334
)
328335

329-
return self.binner, self.grouper, self.obj
336+
# error: Incompatible return value type (got "Tuple[None, None, None]",
337+
# expected "Tuple[Any, BaseGrouper, FrameOrSeries]")
338+
return self.binner, self.grouper, self.obj # type: ignore[return-value]
330339

331340
@final
332-
def _set_grouper(self, obj: FrameOrSeries, sort: bool = False):
341+
def _set_grouper(self, obj: NDFrame, sort: bool = False):
333342
"""
334343
given an object and the specifications, setup the internal grouper
335344
for this particular specification
@@ -459,7 +468,7 @@ def __init__(
459468
self,
460469
index: Index,
461470
grouper=None,
462-
obj: FrameOrSeries | None = None,
471+
obj: NDFrame | None = None,
463472
level=None,
464473
sort: bool = True,
465474
observed: bool = False,
@@ -501,11 +510,9 @@ def __init__(
501510
# what key/level refer to exactly, don't need to
502511
# check again as we have by this point converted these
503512
# to an actual value (rather than a pd.Grouper)
513+
assert self.obj is not None # for mypy
504514
_, newgrouper, newobj = self.grouping_vector._get_grouper(
505-
# error: Value of type variable "FrameOrSeries" of "_get_grouper"
506-
# of "Grouper" cannot be "Optional[FrameOrSeries]"
507-
self.obj, # type: ignore[type-var]
508-
validate=False,
515+
self.obj, validate=False
509516
)
510517
self.obj = newobj
511518

pandas/core/groupby/ops.py

+10-8
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import collections
1111
import functools
1212
from typing import (
13+
Callable,
1314
Generic,
1415
Hashable,
1516
Iterator,
@@ -29,7 +30,6 @@
2930
from pandas._typing import (
3031
ArrayLike,
3132
DtypeObj,
32-
F,
3333
FrameOrSeries,
3434
Shape,
3535
npt,
@@ -700,7 +700,7 @@ def get_iterator(
700700
yield key, group.__finalize__(data, method="groupby")
701701

702702
@final
703-
def _get_splitter(self, data: FrameOrSeries, axis: int = 0) -> DataSplitter:
703+
def _get_splitter(self, data: NDFrame, axis: int = 0) -> DataSplitter:
704704
"""
705705
Returns
706706
-------
@@ -732,7 +732,9 @@ def group_keys_seq(self):
732732
return get_flattened_list(ids, ngroups, self.levels, self.codes)
733733

734734
@final
735-
def apply(self, f: F, data: FrameOrSeries, axis: int = 0) -> tuple[list, bool]:
735+
def apply(
736+
self, f: Callable, data: DataFrame | Series, axis: int = 0
737+
) -> tuple[list, bool]:
736738
mutated = self.mutated
737739
splitter = self._get_splitter(data, axis=axis)
738740
group_keys = self.group_keys_seq
@@ -918,7 +920,7 @@ def _cython_operation(
918920

919921
@final
920922
def agg_series(
921-
self, obj: Series, func: F, preserve_dtype: bool = False
923+
self, obj: Series, func: Callable, preserve_dtype: bool = False
922924
) -> ArrayLike:
923925
"""
924926
Parameters
@@ -960,7 +962,7 @@ def agg_series(
960962

961963
@final
962964
def _aggregate_series_pure_python(
963-
self, obj: Series, func: F
965+
self, obj: Series, func: Callable
964966
) -> npt.NDArray[np.object_]:
965967
ids, _, ngroups = self.group_info
966968

@@ -1061,7 +1063,7 @@ def _get_grouper(self):
10611063
"""
10621064
return self
10631065

1064-
def get_iterator(self, data: FrameOrSeries, axis: int = 0):
1066+
def get_iterator(self, data: NDFrame, axis: int = 0):
10651067
"""
10661068
Groupby iterator
10671069
@@ -1142,7 +1144,7 @@ def groupings(self) -> list[grouper.Grouping]:
11421144
ping = grouper.Grouping(lev, lev, in_axis=False, level=None)
11431145
return [ping]
11441146

1145-
def _aggregate_series_fast(self, obj: Series, func: F) -> np.ndarray:
1147+
def _aggregate_series_fast(self, obj: Series, func: Callable) -> np.ndarray:
11461148
# -> np.ndarray[object]
11471149
raise NotImplementedError(
11481150
"This should not be reached; use _aggregate_series_pure_python"
@@ -1241,7 +1243,7 @@ def _chop(self, sdata: DataFrame, slice_obj: slice) -> DataFrame:
12411243

12421244

12431245
def get_splitter(
1244-
data: FrameOrSeries, labels: np.ndarray, ngroups: int, axis: int = 0
1246+
data: NDFrame, labels: np.ndarray, ngroups: int, axis: int = 0
12451247
) -> DataSplitter:
12461248
if isinstance(data, Series):
12471249
klass: type[DataSplitter] = SeriesSplitter

pandas/core/resample.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from datetime import timedelta
55
from textwrap import dedent
66
from typing import (
7+
TYPE_CHECKING,
78
Callable,
89
Hashable,
910
Literal,
@@ -90,6 +91,12 @@
9091
Tick,
9192
)
9293

94+
if TYPE_CHECKING:
95+
from pandas import (
96+
DataFrame,
97+
Series,
98+
)
99+
93100
_shared_docs_kwargs: dict[str, str] = {}
94101

95102

@@ -135,7 +142,7 @@ class Resampler(BaseGroupBy, PandasObject):
135142

136143
def __init__(
137144
self,
138-
obj: FrameOrSeries,
145+
obj: DataFrame | Series,
139146
groupby: TimeGrouper,
140147
axis: int = 0,
141148
kind=None,

pandas/core/reshape/merge.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@
2626
from pandas._typing import (
2727
ArrayLike,
2828
DtypeObj,
29-
FrameOrSeries,
3029
IndexLabel,
3130
Suffixes,
3231
npt,
@@ -2259,7 +2258,7 @@ def _any(x) -> bool:
22592258
return x is not None and com.any_not_none(*x)
22602259

22612260

2262-
def _validate_operand(obj: FrameOrSeries) -> DataFrame:
2261+
def _validate_operand(obj: DataFrame | Series) -> DataFrame:
22632262
if isinstance(obj, ABCDataFrame):
22642263
return obj
22652264
elif isinstance(obj, ABCSeries):

pandas/core/sample.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,22 @@
33
"""
44
from __future__ import annotations
55

6+
from typing import TYPE_CHECKING
7+
68
import numpy as np
79

810
from pandas._libs import lib
9-
from pandas._typing import FrameOrSeries
1011

1112
from pandas.core.dtypes.generic import (
1213
ABCDataFrame,
1314
ABCSeries,
1415
)
1516

17+
if TYPE_CHECKING:
18+
from pandas.core.generic import NDFrame
19+
1620

17-
def preprocess_weights(obj: FrameOrSeries, weights, axis: int) -> np.ndarray:
21+
def preprocess_weights(obj: NDFrame, weights, axis: int) -> np.ndarray:
1822
"""
1923
Process and validate the `weights` argument to `NDFrame.sample` and
2024
`.GroupBy.sample`.

0 commit comments

Comments
 (0)