diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 2c96f1ef020ac..e228d20b359c6 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -10,6 +10,7 @@ TYPE_CHECKING, Any, Literal, + TypeAlias, cast, ) @@ -71,7 +72,7 @@ from pandas.core.resample import Resampler from pandas.core.window.rolling import BaseWindow -ResType = dict[int, Any] +ResType: TypeAlias = dict[int, Any] class BaseExecutionEngine(abc.ABC): diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 994d7b1d0081c..9a723a88941b6 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -10,6 +10,7 @@ TYPE_CHECKING, Any, Literal, + TypeAlias, Union, cast, final, @@ -161,7 +162,7 @@ TimedeltaArray, ) -DTScalarOrNaT = Union[DatetimeLikeScalar, NaTType] +DTScalarOrNaT: TypeAlias = DatetimeLikeScalar | NaTType def _make_unpacked_invalid_op(op_name: str): @@ -386,7 +387,7 @@ def __getitem__(self, key: PositionalIndexer2D) -> Self | DTScalarOrNaT: # Use cast as we know we will get back a DatetimeLikeArray or DTScalar, # but skip evaluating the Union at runtime for performance # (see https://github.com/pandas-dev/pandas/pull/44624) - result = cast("Union[Self, DTScalarOrNaT]", super().__getitem__(key)) + result = cast(Union[Self, DTScalarOrNaT], super().__getitem__(key)) if lib.is_scalar(result): return result else: diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 6cb79e915c78b..4bcbe2eedee47 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -9,7 +9,7 @@ from typing import ( TYPE_CHECKING, Literal, - Union, + TypeAlias, overload, ) @@ -109,8 +109,8 @@ ) -IntervalSide = Union[TimeArrayLike, np.ndarray] -IntervalOrNA = Union[Interval, float] +IntervalSide: TypeAlias = TimeArrayLike | np.ndarray +IntervalOrNA: TypeAlias = Interval | float _interval_shared_docs: dict[str, str] = {} diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index 9668981df827b..7264efa3298d9 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -4,7 +4,6 @@ import re from typing import ( TYPE_CHECKING, - Union, ) import warnings @@ -63,9 +62,6 @@ from pandas import Series -ArrowStringScalarOrNAT = Union[str, libmissing.NAType] - - def _chk_pyarrow_available() -> None: if pa_version_under10p1: msg = "pyarrow>=10.0.1 is required for PyArrow backed ArrowExtensionArray." diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 49b80337c700e..b2531e2abf7f1 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -17,8 +17,8 @@ Any, Literal, NamedTuple, + TypeAlias, TypeVar, - Union, cast, ) import warnings @@ -102,7 +102,7 @@ from pandas.core.generic import NDFrame # TODO(typing) the return value on this callable should be any *scalar*. -AggScalar = Union[str, Callable[..., Any]] +AggScalar: TypeAlias = str | Callable[..., Any] # TODO: validate types on ScalarResult and move to _typing # Blocked from using by https://github.com/python/mypy/issues/1484 # See note at _mangle_lambda_list diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 3daee98371844..f29423ce5e77c 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -26,6 +26,7 @@ class providing the base-class of operations. from typing import ( TYPE_CHECKING, Literal, + TypeAlias, TypeVar, Union, cast, @@ -449,13 +450,13 @@ def f(self): return attr -_KeysArgType = Union[ - Hashable, - list[Hashable], - Callable[[Hashable], Hashable], - list[Callable[[Hashable], Hashable]], - Mapping[Hashable, Hashable], -] +_KeysArgType: TypeAlias = ( + Hashable + | list[Hashable] + | Callable[[Hashable], Hashable] + | list[Callable[[Hashable], Hashable]] + | Mapping[Hashable, Hashable] +) class BaseGroupBy(PandasObject, SelectionMixin[NDFrameT], GroupByIndexingMixin): @@ -957,9 +958,8 @@ def __iter__(self) -> Iterator[tuple[Hashable, NDFrameT]]: level = self.level result = self._grouper.get_iterator(self._selected_obj) # mypy: Argument 1 to "len" has incompatible type "Hashable"; expected "Sized" - if ( - (is_list_like(level) and len(level) == 1) # type: ignore[arg-type] - or (isinstance(keys, list) and len(keys) == 1) + if (is_list_like(level) and len(level) == 1) or ( # type: ignore[arg-type] + isinstance(keys, list) and len(keys) == 1 ): # GH#42795 - when keys is a list, return tuples even when length is 1 result = (((key,), group) for key, group in result) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 34a437ba40bd8..994dcd4618a1c 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -5,7 +5,6 @@ from typing import ( TYPE_CHECKING, Any, - TypeVar, cast, final, ) @@ -83,6 +82,7 @@ Axis, AxisInt, Self, + T, npt, ) @@ -91,7 +91,6 @@ Series, ) -T = TypeVar("T") # "null slice" _NS = slice(None, None) _one_ellipsis_message = "indexer may only contain one '...' entry" diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 0a10001a3113f..1b236deff330d 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -6,6 +6,7 @@ from itertools import islice from typing import ( TYPE_CHECKING, + TypeAlias, TypedDict, Union, cast, @@ -93,13 +94,12 @@ # --------------------------------------------------------------------- # types used in annotations -ArrayConvertible = Union[list, tuple, AnyArrayLike] -Scalar = Union[float, str] -DatetimeScalar = Union[Scalar, date, np.datetime64] +ArrayConvertible: TypeAlias = list | tuple | AnyArrayLike +Scalar: TypeAlias = float | str +DatetimeScalar: TypeAlias = Scalar | date | np.datetime64 -DatetimeScalarOrArrayConvertible = Union[DatetimeScalar, ArrayConvertible] - -DatetimeDictArg = Union[list[Scalar], tuple[Scalar, ...], AnyArrayLike] +DatetimeScalarOrArrayConvertible: TypeAlias = DatetimeScalar | ArrayConvertible +DatetimeDictArg: TypeAlias = list[Scalar] | tuple[Scalar, ...] | AnyArrayLike class YearMonthDayDict(TypedDict, total=True): diff --git a/pandas/io/excel/_calamine.py b/pandas/io/excel/_calamine.py index b8994e679d4b1..0bdd2b42aad51 100644 --- a/pandas/io/excel/_calamine.py +++ b/pandas/io/excel/_calamine.py @@ -9,7 +9,7 @@ from typing import ( TYPE_CHECKING, Any, - Union, + TypeAlias, ) from pandas.compat._optional import import_optional_dependency @@ -34,7 +34,7 @@ StorageOptions, ) -_CellValue = Union[int, float, str, bool, time, date, datetime, timedelta] +_CellValue: TypeAlias = int | float | str | bool | time | date | datetime | timedelta class CalamineReader(BaseExcelReader["CalamineWorkbook"]): diff --git a/pandas/io/formats/printing.py b/pandas/io/formats/printing.py index ab27321ffe83c..9de5ac071495b 100644 --- a/pandas/io/formats/printing.py +++ b/pandas/io/formats/printing.py @@ -14,8 +14,8 @@ from typing import ( TYPE_CHECKING, Any, + TypeAlias, TypeVar, - Union, ) from unicodedata import east_asian_width @@ -27,7 +27,7 @@ if TYPE_CHECKING: from pandas._typing import ListLike -EscapeChars = Union[Mapping[str, str], Iterable[str]] +EscapeChars: TypeAlias = Mapping[str, str] | Iterable[str] _KT = TypeVar("_KT") _VT = TypeVar("_VT") diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index 6752c83d5169b..0747e7c84e1b0 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -11,9 +11,8 @@ TYPE_CHECKING, Any, DefaultDict, - Optional, + TypeAlias, TypedDict, - Union, ) from uuid import uuid4 @@ -50,11 +49,11 @@ jinja2 = import_optional_dependency("jinja2", extra="DataFrame.style requires jinja2.") from markupsafe import escape as escape_html # markupsafe is jinja2 dependency -BaseFormatter = Union[str, Callable] -ExtFormatter = Union[BaseFormatter, dict[Any, Optional[BaseFormatter]]] -CSSPair = tuple[str, Union[str, float]] -CSSList = list[CSSPair] -CSSProperties = Union[str, CSSList] +BaseFormatter: TypeAlias = str | Callable +ExtFormatter: TypeAlias = BaseFormatter | dict[Any, BaseFormatter | None] +CSSPair: TypeAlias = tuple[str, str | float] +CSSList: TypeAlias = list[CSSPair] +CSSProperties: TypeAlias = str | CSSList class CSSDict(TypedDict): @@ -62,8 +61,8 @@ class CSSDict(TypedDict): props: CSSProperties -CSSStyles = list[CSSDict] -Subset = Union[slice, Sequence, Index] +CSSStyles: TypeAlias = list[CSSDict] +Subset = slice | Sequence | Index class StylerRenderer: diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index c58b4a4be6df1..64a05c87e0f80 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -20,6 +20,7 @@ Any, Final, Literal, + TypeAlias, cast, overload, ) @@ -160,7 +161,7 @@ def _ensure_str(name): return name -Term = PyTablesExpr +Term: TypeAlias = PyTablesExpr def _ensure_term(where, scope_level: int): diff --git a/pandas/tests/io/pytables/test_errors.py b/pandas/tests/io/pytables/test_errors.py index b28101c09820f..23932b6092998 100644 --- a/pandas/tests/io/pytables/test_errors.py +++ b/pandas/tests/io/pytables/test_errors.py @@ -45,7 +45,7 @@ def test_pass_spec_to_storer(setup_path): "format store. this store must be selected in its entirety" ) with pytest.raises(TypeError, match=msg): - store.select("df", where=[("columns=A")]) + store.select("df", where=["columns=A"]) def test_table_index_incompatible_dtypes(setup_path): diff --git a/pandas/tests/io/pytables/test_select.py b/pandas/tests/io/pytables/test_select.py index 5e76aae28c147..0dffb284fa6d2 100644 --- a/pandas/tests/io/pytables/test_select.py +++ b/pandas/tests/io/pytables/test_select.py @@ -143,7 +143,7 @@ def test_select(setup_path): tm.assert_frame_equal(expected, result) # equivalently - result = store.select("df", [("columns=['A', 'B']")]) + result = store.select("df", ["columns=['A', 'B']"]) expected = df.reindex(columns=["A", "B"]) tm.assert_frame_equal(expected, result) diff --git a/pandas/util/version/__init__.py b/pandas/util/version/__init__.py index bd741140f6542..15696c9292eda 100644 --- a/pandas/util/version/__init__.py +++ b/pandas/util/version/__init__.py @@ -13,7 +13,7 @@ Any, NamedTuple, SupportsInt, - Union, + TypeAlias, ) __all__ = ["VERSION_PATTERN", "InvalidVersion", "Version", "parse"] @@ -77,14 +77,14 @@ def __neg__(self: object) -> InfinityType: NegativeInfinity = NegativeInfinityType() -LocalType = tuple[Union[int, str], ...] +LocalType: TypeAlias = tuple[int | str, ...] -CmpPrePostDevType = Union[InfinityType, NegativeInfinityType, tuple[str, int]] -CmpLocalType = Union[ - NegativeInfinityType, - tuple[Union[tuple[int, str], tuple[NegativeInfinityType, Union[int, str]]], ...], -] -CmpKey = tuple[ +CmpPrePostDevType: TypeAlias = InfinityType | NegativeInfinityType | tuple[str, int] +CmpLocalType: TypeAlias = ( + NegativeInfinityType + | tuple[tuple[int, str] | tuple[NegativeInfinityType, int | str], ...] +) +CmpKey: TypeAlias = tuple[ int, tuple[int, ...], CmpPrePostDevType, @@ -92,7 +92,7 @@ def __neg__(self: object) -> InfinityType: CmpPrePostDevType, CmpLocalType, ] -VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool] +VersionComparisonMethod: TypeAlias = Callable[[CmpKey, CmpKey], bool] class _Version(NamedTuple):