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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
Expand Up @@ -10,6 +10,7 @@
TYPE_CHECKING,
Any,
Literal,
TypeAlias,
cast,
)

Expand Down Expand Up @@ -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):
Expand Down
5 changes: 3 additions & 2 deletions pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
TYPE_CHECKING,
Any,
Literal,
TypeAlias,
Union,
cast,
final,
Expand Down Expand Up @@ -161,7 +162,7 @@
TimedeltaArray,
)

DTScalarOrNaT = Union[DatetimeLikeScalar, NaTType]
DTScalarOrNaT: TypeAlias = DatetimeLikeScalar | NaTType


def _make_unpacked_invalid_op(op_name: str):
Expand Down Expand Up @@ -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:
Expand Down
6 changes: 3 additions & 3 deletions pandas/core/arrays/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from typing import (
TYPE_CHECKING,
Literal,
Union,
TypeAlias,
overload,
)

Expand Down Expand Up @@ -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] = {}

Expand Down
4 changes: 0 additions & 4 deletions pandas/core/arrays/string_arrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import re
from typing import (
TYPE_CHECKING,
Union,
)
import warnings

Expand Down Expand Up @@ -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."
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
Any,
Literal,
NamedTuple,
TypeAlias,
TypeVar,
Union,
cast,
)
import warnings
Expand Down Expand Up @@ -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
Expand Down
20 changes: 10 additions & 10 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class providing the base-class of operations.
from typing import (
TYPE_CHECKING,
Literal,
TypeAlias,
TypeVar,
Union,
cast,
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)
Expand Down
3 changes: 1 addition & 2 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from typing import (
TYPE_CHECKING,
Any,
TypeVar,
cast,
final,
)
Expand Down Expand Up @@ -83,6 +82,7 @@
Axis,
AxisInt,
Self,
T,
npt,
)

Expand All @@ -91,7 +91,6 @@
Series,
)

T = TypeVar("T")
# "null slice"
_NS = slice(None, None)
_one_ellipsis_message = "indexer may only contain one '...' entry"
Expand Down
12 changes: 6 additions & 6 deletions pandas/core/tools/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from itertools import islice
from typing import (
TYPE_CHECKING,
TypeAlias,
TypedDict,
Union,
cast,
Expand Down Expand Up @@ -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):
Expand Down
4 changes: 2 additions & 2 deletions pandas/io/excel/_calamine.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from typing import (
TYPE_CHECKING,
Any,
Union,
TypeAlias,
)

from pandas.compat._optional import import_optional_dependency
Expand All @@ -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"]):
Expand Down
4 changes: 2 additions & 2 deletions pandas/io/formats/printing.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
from typing import (
TYPE_CHECKING,
Any,
TypeAlias,
TypeVar,
Union,
)
from unicodedata import east_asian_width

Expand All @@ -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")

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

Expand Down Expand Up @@ -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:
Expand Down
3 changes: 2 additions & 1 deletion pandas/io/pytables.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
Any,
Final,
Literal,
TypeAlias,
cast,
overload,
)
Expand Down Expand Up @@ -160,7 +161,7 @@ def _ensure_str(name):
return name


Term = PyTablesExpr
Term: TypeAlias = PyTablesExpr


def _ensure_term(where, scope_level: int):
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/io/pytables/test_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/io/pytables/test_select.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

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

__all__ = ["VERSION_PATTERN", "InvalidVersion", "Version", "parse"]
Expand Down Expand Up @@ -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):
Expand Down
Loading