Skip to content

Commit 7bcb0c4

Browse files
authored
Y026: explicitly declare type aliases as TypeAlias (#349)
1 parent cd62cb8 commit 7bcb0c4

18 files changed

+170
-137
lines changed

.pre-commit-config.yaml

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ repos:
3030
- flake8-pyi==22.8.2
3131
types: [pyi]
3232
args: [
33-
--ignore=E301 E302 E305 E402 E501 E701 E704 F401 F811 W503 Y019 Y026 Y027 Y034 Y037 Y041,
33+
--ignore=E301 E302 E305 E402 E501 E701 E704 F401 F811 W503 Y019 Y027 Y034 Y037 Y041 Y042,
3434
# TypeVars in private files are already private
3535
--per-file-ignores=_*.pyi:Y001
3636
]

pandas-stubs/_libs/tslibs/nattype.pyi

+4-1
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,17 @@ from datetime import (
66
from typing import Union
77

88
import numpy as np
9+
from typing_extensions import TypeAlias
910

1011
from pandas._libs.tslibs.period import Period
1112

1213
NaT: NaTType
1314
iNaT: int
1415
nat_strings: set[str]
1516

16-
_NaTComparisonTypes = Union[datetime, timedelta, Period, np.datetime64, np.timedelta64]
17+
_NaTComparisonTypes: TypeAlias = Union[
18+
datetime, timedelta, Period, np.datetime64, np.timedelta64
19+
]
1720

1821
class _NatComparison:
1922
def __call__(self, other: _NaTComparisonTypes) -> bool: ...

pandas-stubs/_libs/tslibs/timedeltas.pyi

+2-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ from typing import (
77
)
88

99
import numpy as np
10+
from typing_extensions import TypeAlias
1011

1112
from pandas._libs.tslibs import (
1213
NaTType,
@@ -16,7 +17,7 @@ from pandas._typing import npt
1617

1718
# This should be kept consistent with the keys in the dict timedelta_abbrevs
1819
# in pandas/_libs/tslibs/timedeltas.pyx
19-
UnitChoices = Literal[
20+
UnitChoices: TypeAlias = Literal[
2021
"Y",
2122
"y",
2223
"M",

pandas-stubs/_typing.pyi

+97-92
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,8 @@
11
from builtins import type as type_t
22
import datetime
3-
from io import (
4-
BufferedIOBase,
5-
RawIOBase,
6-
TextIOBase,
7-
TextIOWrapper,
8-
)
9-
from mmap import mmap
103
from os import PathLike
114
from typing import (
12-
IO,
135
Any,
14-
AnyStr,
156
Callable,
167
Hashable,
178
Iterator,
@@ -32,6 +23,7 @@ from pandas.core.generic import NDFrame
3223
from pandas.core.groupby.grouper import Grouper
3324
from pandas.core.indexes.base import Index
3425
from pandas.core.series import Series
26+
from typing_extensions import TypeAlias
3527

3628
from pandas._libs.tslibs import (
3729
Period,
@@ -43,22 +35,28 @@ from pandas.core.dtypes.dtypes import ExtensionDtype
4335

4436
from pandas.io.formats.format import EngFormatter
4537

46-
ArrayLike = Union[ExtensionArray, np.ndarray]
47-
AnyArrayLike = Union[Index, Series, np.ndarray]
48-
PythonScalar = Union[str, bool, complex]
38+
ArrayLike: TypeAlias = Union[ExtensionArray, np.ndarray]
39+
AnyArrayLike: TypeAlias = Union[Index, Series, np.ndarray]
40+
PythonScalar: TypeAlias = Union[str, bool, complex]
4941
DatetimeLikeScalar = TypeVar("DatetimeLikeScalar", Period, Timestamp, Timedelta)
50-
PandasScalar = Union[bytes, datetime.date, datetime.datetime, datetime.timedelta]
51-
# Scalar = Union[PythonScalar, PandasScalar]
42+
PandasScalar: TypeAlias = Union[
43+
bytes, datetime.date, datetime.datetime, datetime.timedelta
44+
]
45+
# Scalar: TypeAlias = Union[PythonScalar, PandasScalar]
5246

53-
DatetimeLike = Union[datetime.date, datetime.datetime, np.datetime64, Timestamp]
47+
DatetimeLike: TypeAlias = Union[
48+
datetime.date, datetime.datetime, np.datetime64, Timestamp
49+
]
5450

5551
# dtypes
56-
NpDtype = Union[str, np.dtype[np.generic], type[Union[str, complex, bool, object]]]
57-
Dtype = Union[ExtensionDtype, NpDtype]
58-
AstypeArg = Union[ExtensionDtype, npt.DTypeLike]
52+
NpDtype: TypeAlias = Union[
53+
str, np.dtype[np.generic], type[Union[str, complex, bool, object]]
54+
]
55+
Dtype: TypeAlias = Union[ExtensionDtype, NpDtype]
56+
AstypeArg: TypeAlias = Union[ExtensionDtype, npt.DTypeLike]
5957
# DtypeArg specifies all allowable dtypes in a functions its dtype argument
60-
DtypeArg = Union[Dtype, dict[Any, Dtype]]
61-
DtypeObj = Union[np.dtype[np.generic], ExtensionDtype]
58+
DtypeArg: TypeAlias = Union[Dtype, dict[Any, Dtype]]
59+
DtypeObj: TypeAlias = Union[np.dtype[np.generic], ExtensionDtype]
6260

6361
# filenames and file-like-objects
6462
AnyStr_cov = TypeVar("AnyStr_cov", str, bytes, covariant=True)
@@ -91,47 +89,48 @@ class ReadCsvBuffer(ReadBuffer[AnyStr_cov], Protocol[AnyStr_cov]):
9189
class WriteExcelBuffer(WriteBuffer[bytes], Protocol):
9290
def truncate(self, size: int | None = ...) -> int: ...
9391

94-
FilePath = Union[str, PathLike[str]]
95-
FilePathOrBuffer = Union[
96-
FilePath, IO[AnyStr], RawIOBase, BufferedIOBase, TextIOBase, TextIOWrapper, mmap
97-
]
98-
99-
Axis = Union[str, int]
100-
IndexLabel = Union[Hashable, Sequence[Hashable]]
101-
Label = Optional[Hashable]
102-
Level = Union[Hashable, int]
103-
Suffixes = tuple[Optional[str], Optional[str]]
104-
Ordered = Optional[bool]
105-
JSONSerializable = Union[PythonScalar, list, dict]
106-
Axes = Union[AnyArrayLike, list, dict, range]
107-
Renamer = Union[Mapping[Any, Label], Callable[[Any], Label]]
92+
FilePath: TypeAlias = Union[str, PathLike[str]]
93+
94+
Axis: TypeAlias = Union[str, int]
95+
IndexLabel: TypeAlias = Union[Hashable, Sequence[Hashable]]
96+
Label: TypeAlias = Optional[Hashable]
97+
Level: TypeAlias = Union[Hashable, int]
98+
Suffixes: TypeAlias = tuple[Optional[str], Optional[str]]
99+
Ordered: TypeAlias = Optional[bool]
100+
JSONSerializable: TypeAlias = Union[PythonScalar, list, dict]
101+
Axes: TypeAlias = Union[AnyArrayLike, list, dict, range]
102+
Renamer: TypeAlias = Union[Mapping[Any, Label], Callable[[Any], Label]]
108103
T = TypeVar("T")
109-
FuncType = Callable[..., Any]
104+
FuncType: TypeAlias = Callable[..., Any]
110105
F = TypeVar("F", bound=FuncType)
111106
HashableT = TypeVar("HashableT", bound=Hashable)
112107

113-
AggFuncTypeBase = Union[Callable, str, np.ufunc]
114-
AggFuncTypeDictSeries = dict[Hashable, AggFuncTypeBase]
115-
AggFuncTypeDictFrame = dict[Hashable, Union[AggFuncTypeBase, list[AggFuncTypeBase]]]
116-
AggFuncTypeSeriesToFrame = Union[
108+
AggFuncTypeBase: TypeAlias = Union[Callable, str, np.ufunc]
109+
AggFuncTypeDictSeries: TypeAlias = dict[Hashable, AggFuncTypeBase]
110+
AggFuncTypeDictFrame: TypeAlias = dict[
111+
Hashable, Union[AggFuncTypeBase, list[AggFuncTypeBase]]
112+
]
113+
AggFuncTypeSeriesToFrame: TypeAlias = Union[
117114
list[AggFuncTypeBase],
118115
AggFuncTypeDictSeries,
119116
]
120-
AggFuncTypeFrame = Union[
117+
AggFuncTypeFrame: TypeAlias = Union[
121118
AggFuncTypeBase,
122119
list[AggFuncTypeBase],
123120
AggFuncTypeDictFrame,
124121
]
125122

126-
num = complex
127-
SeriesAxisType = Literal["index", 0] # Restricted subset of _AxisType for series
128-
AxisType = Literal["columns", "index", 0, 1]
123+
num: TypeAlias = complex
124+
SeriesAxisType: TypeAlias = Literal[
125+
"index", 0
126+
] # Restricted subset of _AxisType for series
127+
AxisType: TypeAlias = Literal["columns", "index", 0, 1]
129128
DtypeNp = TypeVar("DtypeNp", bound=np.dtype[np.generic])
130-
KeysArgType = Any
129+
KeysArgType: TypeAlias = Any
131130
ListLike = TypeVar("ListLike", Sequence, np.ndarray, "Series", "Index")
132-
ListLikeU = Union[Sequence, np.ndarray, Series, Index]
133-
StrLike = Union[str, np.str_]
134-
Scalar = Union[
131+
ListLikeU: TypeAlias = Union[Sequence, np.ndarray, Series, Index]
132+
StrLike: TypeAlias = Union[str, np.str_]
133+
Scalar: TypeAlias = Union[
135134
str,
136135
bytes,
137136
datetime.date,
@@ -146,14 +145,14 @@ Scalar = Union[
146145
]
147146
ScalarT = TypeVar("ScalarT", bound=Scalar)
148147
# Refine the definitions below in 3.9 to use the specialized type.
149-
np_ndarray_int64 = npt.NDArray[np.int64]
150-
np_ndarray_int = npt.NDArray[np.signedinteger]
151-
np_ndarray_anyint = npt.NDArray[np.integer]
152-
np_ndarray_bool = npt.NDArray[np.bool_]
153-
np_ndarray_str = npt.NDArray[np.str_]
154-
155-
IndexType = Union[slice, np_ndarray_int64, Index, list[int], Series[int]]
156-
MaskType = Union[Series[bool], np_ndarray_bool, list[bool]]
148+
np_ndarray_int64: TypeAlias = npt.NDArray[np.int64]
149+
np_ndarray_int: TypeAlias = npt.NDArray[np.signedinteger]
150+
np_ndarray_anyint: TypeAlias = npt.NDArray[np.integer]
151+
np_ndarray_bool: TypeAlias = npt.NDArray[np.bool_]
152+
np_ndarray_str: TypeAlias = npt.NDArray[np.str_]
153+
154+
IndexType: TypeAlias = Union[slice, np_ndarray_int64, Index, list[int], Series[int]]
155+
MaskType: TypeAlias = Union[Series[bool], np_ndarray_bool, list[bool]]
157156
# Scratch types for generics
158157
S1 = TypeVar(
159158
"S1",
@@ -177,13 +176,13 @@ T1 = TypeVar(
177176
)
178177
T2 = TypeVar("T2", str, int)
179178

180-
IndexingInt = Union[
179+
IndexingInt: TypeAlias = Union[
181180
int, np.int_, np.integer, np.unsignedinteger, np.signedinteger, np.int8
182181
]
183-
TimestampConvertibleTypes = Union[
182+
TimestampConvertibleTypes: TypeAlias = Union[
184183
Timestamp, datetime.datetime, np.datetime64, np.int64, float, str
185184
]
186-
TimedeltaConvertibleTypes = Union[
185+
TimedeltaConvertibleTypes: TypeAlias = Union[
187186
Timedelta, datetime.timedelta, np.timedelta64, np.int64, float, str
188187
]
189188
# NDFrameT is stricter and ensures that the same subclass of NDFrame always is
@@ -196,39 +195,39 @@ IndexT = TypeVar("IndexT", bound=Index)
196195

197196
# Interval closed type
198197

199-
IntervalClosedType = Literal["left", "right", "both", "neither"]
198+
IntervalClosedType: TypeAlias = Literal["left", "right", "both", "neither"]
200199

201-
DateTimeErrorChoices = Literal["ignore", "raise", "coerce"]
200+
DateTimeErrorChoices: TypeAlias = Literal["ignore", "raise", "coerce"]
202201

203202
# Shared by functions such as drop and astype
204-
IgnoreRaise = Literal["ignore", "raise"]
203+
IgnoreRaise: TypeAlias = Literal["ignore", "raise"]
205204

206205
# for arbitrary kwargs passed during reading/writing files
207-
StorageOptions = Optional[dict[str, Any]]
206+
StorageOptions: TypeAlias = Optional[dict[str, Any]]
208207

209208
# compression keywords and compression
210-
CompressionDict = dict[str, Any]
211-
CompressionOptions = Optional[
209+
CompressionDict: TypeAlias = dict[str, Any]
210+
CompressionOptions: TypeAlias = Optional[
212211
Union[Literal["infer", "gzip", "bz2", "zip", "xz", "zstd"], CompressionDict]
213212
]
214-
FormattersType = Union[
213+
FormattersType: TypeAlias = Union[
215214
list[Callable], tuple[Callable, ...], Mapping[Union[str, int], Callable]
216215
]
217-
FloatFormatType = str | Callable | EngFormatter
216+
FloatFormatType: TypeAlias = str | Callable | EngFormatter
218217
# converters
219-
ConvertersArg = dict[Hashable, Callable[[Dtype], Dtype]]
218+
ConvertersArg: TypeAlias = dict[Hashable, Callable[[Dtype], Dtype]]
220219

221220
# parse_dates
222-
ParseDatesArg = Union[
221+
ParseDatesArg: TypeAlias = Union[
223222
bool, list[Hashable], list[list[Hashable]], dict[Hashable, list[Hashable]]
224223
]
225224

226225
# read_xml parsers
227-
XMLParsers = Literal["lxml", "etree"]
226+
XMLParsers: TypeAlias = Literal["lxml", "etree"]
228227

229228
# Any plain Python or numpy function
230-
Function = Union[np.ufunc, Callable[..., Any]]
231-
GroupByObjectNonScalar = Union[
229+
Function: TypeAlias = Union[np.ufunc, Callable[..., Any]]
230+
GroupByObjectNonScalar: TypeAlias = Union[
232231
tuple,
233232
list[HashableT],
234233
Function,
@@ -244,9 +243,9 @@ GroupByObjectNonScalar = Union[
244243
Grouper,
245244
list[Grouper],
246245
]
247-
GroupByObject = Union[Scalar, GroupByObjectNonScalar]
246+
GroupByObject: TypeAlias = Union[Scalar, GroupByObjectNonScalar]
248247

249-
StataDateFormat = Literal[
248+
StataDateFormat: TypeAlias = Literal[
250249
"tc",
251250
"%tc",
252251
"td",
@@ -263,37 +262,43 @@ StataDateFormat = Literal[
263262
"%ty",
264263
]
265264

266-
FillnaOptions = Literal["backfill", "bfill", "ffill", "pad"]
267-
ReplaceMethod = Literal["pad", "ffill", "bfill"]
268-
SortKind = Literal["quicksort", "mergesort", "heapsort", "stable"]
269-
NaPosition = Literal["first", "last"]
270-
MergeHow = Literal["left", "right", "outer", "inner"]
271-
JsonFrameOrient = Literal["split", "records", "index", "columns", "values", "table"]
272-
JsonSeriesOrient = Literal["split", "records", "index"]
265+
FillnaOptions: TypeAlias = Literal["backfill", "bfill", "ffill", "pad"]
266+
ReplaceMethod: TypeAlias = Literal["pad", "ffill", "bfill"]
267+
SortKind: TypeAlias = Literal["quicksort", "mergesort", "heapsort", "stable"]
268+
NaPosition: TypeAlias = Literal["first", "last"]
269+
MergeHow: TypeAlias = Literal["left", "right", "outer", "inner"]
270+
JsonFrameOrient: TypeAlias = Literal[
271+
"split", "records", "index", "columns", "values", "table"
272+
]
273+
JsonSeriesOrient: TypeAlias = Literal["split", "records", "index"]
273274

274-
TimestampConvention = Literal["start", "end", "s", "e"]
275+
TimestampConvention: TypeAlias = Literal["start", "end", "s", "e"]
275276

276-
CSVEngine = Literal["c", "python", "pyarrow", "python-fwf"]
277-
CSVQuoting = Literal[0, 1, 2, 3]
277+
CSVEngine: TypeAlias = Literal["c", "python", "pyarrow", "python-fwf"]
278+
CSVQuoting: TypeAlias = Literal[0, 1, 2, 3]
278279

279-
HDFCompLib = Literal["zlib", "lzo", "bzip2", "blosc"]
280-
ParquetEngine = Literal["auto", "pyarrow", "fastparquet"]
281-
FileWriteMode = Literal[
280+
HDFCompLib: TypeAlias = Literal["zlib", "lzo", "bzip2", "blosc"]
281+
ParquetEngine: TypeAlias = Literal["auto", "pyarrow", "fastparquet"]
282+
FileWriteMode: TypeAlias = Literal[
282283
"a", "w", "x", "at", "wt", "xt", "ab", "wb", "xb", "w+", "w+b", "a+", "a+b"
283284
]
284-
ColspaceArgType = str | int | Sequence[int | str] | Mapping[Hashable, str | int]
285+
ColspaceArgType: TypeAlias = (
286+
str | int | Sequence[int | str] | Mapping[Hashable, str | int]
287+
)
285288

286289
# Windowing rank methods
287-
WindowingRankType = Literal["average", "min", "max"]
288-
WindowingEngine = Union[Literal["cython", "numba"], None]
290+
WindowingRankType: TypeAlias = Literal["average", "min", "max"]
291+
WindowingEngine: TypeAlias = Union[Literal["cython", "numba"], None]
289292

290293
class _WindowingNumbaKwargs(TypedDict, total=False):
291294
nopython: bool
292295
nogil: bool
293296
parallel: bool
294297

295-
WindowingEngineKwargs = Union[_WindowingNumbaKwargs, None]
296-
QuantileInterpolation = Literal["linear", "lower", "higher", "midpoint", "nearest"]
298+
WindowingEngineKwargs: TypeAlias = Union[_WindowingNumbaKwargs, None]
299+
QuantileInterpolation: TypeAlias = Literal[
300+
"linear", "lower", "higher", "midpoint", "nearest"
301+
]
297302

298303
class StyleExportDict(TypedDict, total=False):
299304
apply: Any
@@ -305,6 +310,6 @@ class StyleExportDict(TypedDict, total=False):
305310
hide_column_names: bool
306311
css: dict[str, str | int]
307312

308-
CalculationMethod = Literal["single", "table"]
313+
CalculationMethod: TypeAlias = Literal["single", "table"]
309314

310315
__all__ = ["npt", "type_t"]

pandas-stubs/_version.pyi

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@ version_json: str = ...
44

55
def get_versions(): ...
66

7-
_stub_version = Literal["1.5.0.220926"]
7+
_stub_version: Literal["1.5.0.220926"]

pandas-stubs/core/dtypes/common.pyi

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ from typing import Union
22

33
import numpy as np
44
import pandas as pd
5+
from typing_extensions import TypeAlias
56

67
from pandas._typing import (
78
ArrayLike,
@@ -28,7 +29,7 @@ from pandas.core.dtypes.inference import (
2829
is_scalar as is_scalar,
2930
)
3031

31-
_ArrayOrDtype = Union[ArrayLike, npt.DTypeLike, pd.Series, pd.DataFrame]
32+
_ArrayOrDtype: TypeAlias = Union[ArrayLike, npt.DTypeLike, pd.Series, pd.DataFrame]
3233

3334
def is_object_dtype(arr_or_dtype: _ArrayOrDtype) -> bool: ...
3435
def is_sparse(arr: ArrayLike | pd.Series | pd.DataFrame) -> bool: ...

pandas-stubs/core/dtypes/generic.pyi

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from pandas import Series
22
from pandas.core.arrays import ExtensionArray
3+
from typing_extensions import TypeAlias
34

4-
ABCSeries = type[Series]
5-
ABCExtensionArray = type[ExtensionArray]
5+
ABCSeries: TypeAlias = type[Series]
6+
ABCExtensionArray: TypeAlias = type[ExtensionArray]

0 commit comments

Comments
 (0)