Skip to content

Use TypeAlias in code where types are declared #61504

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 1, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion pandas/core/apply.py
Original file line number Diff line number Diff line change
@@ -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):
5 changes: 3 additions & 2 deletions pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
@@ -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:
6 changes: 3 additions & 3 deletions pandas/core/arrays/interval.py
Original file line number Diff line number Diff line change
@@ -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] = {}

4 changes: 0 additions & 4 deletions pandas/core/arrays/string_arrow.py
Original file line number Diff line number Diff line change
@@ -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."
4 changes: 2 additions & 2 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
@@ -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
20 changes: 10 additions & 10 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
@@ -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)
3 changes: 1 addition & 2 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
@@ -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"
12 changes: 6 additions & 6 deletions pandas/core/tools/datetimes.py
Original file line number Diff line number Diff line change
@@ -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):
4 changes: 2 additions & 2 deletions pandas/io/excel/_calamine.py
Original file line number Diff line number Diff line change
@@ -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"]):
4 changes: 2 additions & 2 deletions pandas/io/formats/printing.py
Original file line number Diff line number Diff line change
@@ -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")

17 changes: 8 additions & 9 deletions pandas/io/formats/style_render.py
Original file line number Diff line number Diff line change
@@ -11,9 +11,8 @@
TYPE_CHECKING,
Any,
DefaultDict,
Optional,
TypeAlias,
TypedDict,
Union,
)
from uuid import uuid4

@@ -50,20 +49,20 @@
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):
selector: str
props: CSSProperties


CSSStyles = list[CSSDict]
Subset = Union[slice, Sequence, Index]
CSSStyles: TypeAlias = list[CSSDict]
Subset = slice | Sequence | Index


class StylerRenderer:
3 changes: 2 additions & 1 deletion pandas/io/pytables.py
Original file line number Diff line number Diff line change
@@ -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):
2 changes: 1 addition & 1 deletion pandas/tests/io/pytables/test_errors.py
Original file line number Diff line number Diff line change
@@ -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):
2 changes: 1 addition & 1 deletion pandas/tests/io/pytables/test_select.py
Original file line number Diff line number Diff line change
@@ -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)

18 changes: 9 additions & 9 deletions pandas/util/version/__init__.py
Original file line number Diff line number Diff line change
@@ -13,7 +13,7 @@
Any,
NamedTuple,
SupportsInt,
Union,
TypeAlias,
)

__all__ = ["VERSION_PATTERN", "InvalidVersion", "Version", "parse"]
@@ -77,22 +77,22 @@ 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,
CmpPrePostDevType,
CmpPrePostDevType,
CmpLocalType,
]
VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool]
VersionComparisonMethod: TypeAlias = Callable[[CmpKey, CmpKey], bool]


class _Version(NamedTuple):
Loading
Oops, something went wrong.