Skip to content

Commit 024c5ff

Browse files
committed
use TypeAlias. Make internal types private
1 parent 50e23e7 commit 024c5ff

File tree

13 files changed

+105
-105
lines changed

13 files changed

+105
-105
lines changed

pandas/core/apply.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
TYPE_CHECKING,
1111
Any,
1212
Literal,
13+
TypeAlias,
1314
cast,
1415
)
1516

@@ -71,7 +72,7 @@
7172
from pandas.core.resample import Resampler
7273
from pandas.core.window.rolling import BaseWindow
7374

74-
ResType = dict[int, Any]
75+
_ResType: TypeAlias = dict[int, Any]
7576

7677

7778
class BaseExecutionEngine(abc.ABC):
@@ -934,7 +935,7 @@ def validate_values_for_numba(self) -> None:
934935

935936
@abc.abstractmethod
936937
def wrap_results_for_axis(
937-
self, results: ResType, res_index: Index
938+
self, results: _ResType, res_index: Index
938939
) -> DataFrame | Series:
939940
pass
940941

@@ -1163,7 +1164,7 @@ def apply_standard(self):
11631164
# wrap results
11641165
return self.wrap_results(results, res_index)
11651166

1166-
def apply_series_generator(self) -> tuple[ResType, Index]:
1167+
def apply_series_generator(self) -> tuple[_ResType, Index]:
11671168
assert callable(self.func)
11681169

11691170
series_gen = self.series_generator
@@ -1193,7 +1194,7 @@ def apply_series_numba(self):
11931194
results = self.apply_with_numba()
11941195
return results, self.result_index
11951196

1196-
def wrap_results(self, results: ResType, res_index: Index) -> DataFrame | Series:
1197+
def wrap_results(self, results: _ResType, res_index: Index) -> DataFrame | Series:
11971198
from pandas import Series
11981199

11991200
# see if we can infer the results
@@ -1289,7 +1290,7 @@ def result_columns(self) -> Index:
12891290
return self.index
12901291

12911292
def wrap_results_for_axis(
1292-
self, results: ResType, res_index: Index
1293+
self, results: _ResType, res_index: Index
12931294
) -> DataFrame | Series:
12941295
"""return the results for the rows"""
12951296

@@ -1433,7 +1434,7 @@ def result_columns(self) -> Index:
14331434
return self.columns
14341435

14351436
def wrap_results_for_axis(
1436-
self, results: ResType, res_index: Index
1437+
self, results: _ResType, res_index: Index
14371438
) -> DataFrame | Series:
14381439
"""return the results for the columns"""
14391440
result: DataFrame | Series
@@ -1453,7 +1454,7 @@ def wrap_results_for_axis(
14531454

14541455
return result
14551456

1456-
def infer_to_same_shape(self, results: ResType, res_index: Index) -> DataFrame:
1457+
def infer_to_same_shape(self, results: _ResType, res_index: Index) -> DataFrame:
14571458
"""infer the results to the same shape as the input object"""
14581459
result = self.obj._constructor(data=results)
14591460
result = result.T

pandas/core/arrays/datetimelike.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
TYPE_CHECKING,
1111
Any,
1212
Literal,
13+
TypeAlias,
1314
Union,
1415
cast,
1516
final,
@@ -161,7 +162,8 @@
161162
TimedeltaArray,
162163
)
163164

164-
DTScalarOrNaT = Union[DatetimeLikeScalar, NaTType]
165+
# underscore at end because of rule PYI043 that private types should not end with 'T'
166+
_DTScalarOrNaT_: TypeAlias = DatetimeLikeScalar | NaTType
165167

166168

167169
def _make_unpacked_invalid_op(op_name: str):
@@ -236,7 +238,7 @@ def _scalar_type(self) -> type[DatetimeLikeScalar]:
236238
"""
237239
raise AbstractMethodError(self)
238240

239-
def _scalar_from_string(self, value: str) -> DTScalarOrNaT:
241+
def _scalar_from_string(self, value: str) -> _DTScalarOrNaT_:
240242
"""
241243
Construct a scalar type from a string.
242244
@@ -257,7 +259,7 @@ def _scalar_from_string(self, value: str) -> DTScalarOrNaT:
257259
raise AbstractMethodError(self)
258260

259261
def _unbox_scalar(
260-
self, value: DTScalarOrNaT
262+
self, value: _DTScalarOrNaT_
261263
) -> np.int64 | np.datetime64 | np.timedelta64:
262264
"""
263265
Unbox the integer value of a scalar `value`.
@@ -279,7 +281,7 @@ def _unbox_scalar(
279281
"""
280282
raise AbstractMethodError(self)
281283

282-
def _check_compatible_with(self, other: DTScalarOrNaT) -> None:
284+
def _check_compatible_with(self, other: _DTScalarOrNaT_) -> None:
283285
"""
284286
Verify that `self` and `other` are compatible.
285287
@@ -370,23 +372,23 @@ def __array__(
370372
return self._ndarray
371373

372374
@overload
373-
def __getitem__(self, key: ScalarIndexer) -> DTScalarOrNaT: ...
375+
def __getitem__(self, key: ScalarIndexer) -> _DTScalarOrNaT_: ...
374376

375377
@overload
376378
def __getitem__(
377379
self,
378380
key: SequenceIndexer | PositionalIndexerTuple,
379381
) -> Self: ...
380382

381-
def __getitem__(self, key: PositionalIndexer2D) -> Self | DTScalarOrNaT:
383+
def __getitem__(self, key: PositionalIndexer2D) -> Self | _DTScalarOrNaT_:
382384
"""
383385
This getitem defers to the underlying array, which by-definition can
384386
only handle list-likes, slices, and integer scalars
385387
"""
386388
# Use cast as we know we will get back a DatetimeLikeArray or DTScalar,
387389
# but skip evaluating the Union at runtime for performance
388390
# (see https://github.com/pandas-dev/pandas/pull/44624)
389-
result = cast("Union[Self, DTScalarOrNaT]", super().__getitem__(key))
391+
result = cast(Union[Self, _DTScalarOrNaT_], super().__getitem__(key))
390392
if lib.is_scalar(result):
391393
return result
392394
else:

pandas/core/arrays/interval.py

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from typing import (
1010
TYPE_CHECKING,
1111
Literal,
12-
Union,
12+
TypeAlias,
1313
overload,
1414
)
1515

@@ -109,8 +109,8 @@
109109
)
110110

111111

112-
IntervalSide = Union[TimeArrayLike, np.ndarray]
113-
IntervalOrNA = Union[Interval, float]
112+
_IntervalSide: TypeAlias = TimeArrayLike | np.ndarray
113+
_IntervalOrNA: TypeAlias = Interval | float
114114

115115
_interval_shared_docs: dict[str, str] = {}
116116

@@ -216,8 +216,8 @@ def ndim(self) -> Literal[1]:
216216
return 1
217217

218218
# To make mypy recognize the fields
219-
_left: IntervalSide
220-
_right: IntervalSide
219+
_left: _IntervalSide
220+
_right: _IntervalSide
221221
_dtype: IntervalDtype
222222

223223
# ---------------------------------------------------------------------
@@ -234,8 +234,8 @@ def __new__(
234234
data = extract_array(data, extract_numpy=True)
235235

236236
if isinstance(data, cls):
237-
left: IntervalSide = data._left
238-
right: IntervalSide = data._right
237+
left: _IntervalSide = data._left
238+
right: _IntervalSide = data._right
239239
closed = closed or data.closed
240240
dtype = IntervalDtype(left.dtype, closed=closed)
241241
else:
@@ -277,8 +277,8 @@ def __new__(
277277
@classmethod
278278
def _simple_new(
279279
cls,
280-
left: IntervalSide,
281-
right: IntervalSide,
280+
left: _IntervalSide,
281+
right: _IntervalSide,
282282
dtype: IntervalDtype,
283283
) -> Self:
284284
result = IntervalMixin.__new__(cls)
@@ -296,7 +296,7 @@ def _ensure_simple_new_inputs(
296296
closed: IntervalClosedType | None = None,
297297
copy: bool = False,
298298
dtype: Dtype | None = None,
299-
) -> tuple[IntervalSide, IntervalSide, IntervalDtype]:
299+
) -> tuple[_IntervalSide, _IntervalSide, IntervalDtype]:
300300
"""Ensure correctness of input parameters for cls._simple_new."""
301301
from pandas.core.indexes.base import ensure_index
302302

@@ -704,12 +704,12 @@ def __len__(self) -> int:
704704
return len(self._left)
705705

706706
@overload
707-
def __getitem__(self, key: ScalarIndexer) -> IntervalOrNA: ...
707+
def __getitem__(self, key: ScalarIndexer) -> _IntervalOrNA: ...
708708

709709
@overload
710710
def __getitem__(self, key: SequenceIndexer) -> Self: ...
711711

712-
def __getitem__(self, key: PositionalIndexer) -> Self | IntervalOrNA:
712+
def __getitem__(self, key: PositionalIndexer) -> Self | _IntervalOrNA:
713713
key = check_array_indexer(self, key)
714714
left = self._left[key]
715715
right = self._right[key]
@@ -858,7 +858,7 @@ def argsort(
858858
ascending=ascending, kind=kind, na_position=na_position, **kwargs
859859
)
860860

861-
def min(self, *, axis: AxisInt | None = None, skipna: bool = True) -> IntervalOrNA:
861+
def min(self, *, axis: AxisInt | None = None, skipna: bool = True) -> _IntervalOrNA:
862862
nv.validate_minmax_axis(axis, self.ndim)
863863

864864
if not len(self):
@@ -875,7 +875,7 @@ def min(self, *, axis: AxisInt | None = None, skipna: bool = True) -> IntervalOr
875875
indexer = obj.argsort()[0]
876876
return obj[indexer]
877877

878-
def max(self, *, axis: AxisInt | None = None, skipna: bool = True) -> IntervalOrNA:
878+
def max(self, *, axis: AxisInt | None = None, skipna: bool = True) -> _IntervalOrNA:
879879
nv.validate_minmax_axis(axis, self.ndim)
880880

881881
if not len(self):
@@ -1016,8 +1016,10 @@ def _concat_same_type(cls, to_concat: Sequence[IntervalArray]) -> Self:
10161016
raise ValueError("Intervals must all be closed on the same side.")
10171017
closed = closed_set.pop()
10181018

1019-
left: IntervalSide = np.concatenate([interval.left for interval in to_concat])
1020-
right: IntervalSide = np.concatenate([interval.right for interval in to_concat])
1019+
left: _IntervalSide = np.concatenate([interval.left for interval in to_concat])
1020+
right: _IntervalSide = np.concatenate(
1021+
[interval.right for interval in to_concat]
1022+
)
10211023

10221024
left, right, dtype = cls._ensure_simple_new_inputs(left, right, closed=closed)
10231025

@@ -1952,7 +1954,7 @@ def isin(self, values: ArrayLike) -> npt.NDArray[np.bool_]:
19521954
return isin(self.astype(object), values.astype(object))
19531955

19541956
@property
1955-
def _combined(self) -> IntervalSide:
1957+
def _combined(self) -> _IntervalSide:
19561958
# error: Item "ExtensionArray" of "ExtensionArray | ndarray[Any, Any]"
19571959
# has no attribute "reshape" [union-attr]
19581960
left = self.left._values.reshape(-1, 1) # type: ignore[union-attr]

pandas/core/arrays/string_arrow.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import re
55
from typing import (
66
TYPE_CHECKING,
7-
Union,
87
)
98
import warnings
109

@@ -63,9 +62,6 @@
6362
from pandas import Series
6463

6564

66-
ArrowStringScalarOrNAT = Union[str, libmissing.NAType]
67-
68-
6965
def _chk_pyarrow_available() -> None:
7066
if pa_version_under10p1:
7167
msg = "pyarrow>=10.0.1 is required for PyArrow backed ArrowExtensionArray."

pandas/core/groupby/generic.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@
1717
Any,
1818
Literal,
1919
NamedTuple,
20+
TypeAlias,
2021
TypeVar,
21-
Union,
2222
cast,
2323
)
2424
import warnings
@@ -102,7 +102,7 @@
102102
from pandas.core.generic import NDFrame
103103

104104
# TODO(typing) the return value on this callable should be any *scalar*.
105-
AggScalar = Union[str, Callable[..., Any]]
105+
_AggScalar: TypeAlias = str | Callable[..., Any]
106106
# TODO: validate types on ScalarResult and move to _typing
107107
# Blocked from using by https://github.com/python/mypy/issues/1484
108108
# See note at _mangle_lambda_list
@@ -141,7 +141,7 @@ class NamedAgg(NamedTuple):
141141
"""
142142

143143
column: Hashable
144-
aggfunc: AggScalar
144+
aggfunc: _AggScalar
145145

146146

147147
@set_module("pandas.api.typing")

pandas/core/groupby/groupby.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ class providing the base-class of operations.
2626
from typing import (
2727
TYPE_CHECKING,
2828
Literal,
29+
TypeAlias,
2930
TypeVar,
3031
Union,
3132
cast,
@@ -449,13 +450,13 @@ def f(self):
449450
return attr
450451

451452

452-
_KeysArgType = Union[
453-
Hashable,
454-
list[Hashable],
455-
Callable[[Hashable], Hashable],
456-
list[Callable[[Hashable], Hashable]],
457-
Mapping[Hashable, Hashable],
458-
]
453+
_KeysArgType: TypeAlias = (
454+
Hashable
455+
| list[Hashable]
456+
| Callable[[Hashable], Hashable]
457+
| list[Callable[[Hashable], Hashable]]
458+
| Mapping[Hashable, Hashable]
459+
)
459460

460461

461462
class BaseGroupBy(PandasObject, SelectionMixin[NDFrameT], GroupByIndexingMixin):
@@ -957,9 +958,8 @@ def __iter__(self) -> Iterator[tuple[Hashable, NDFrameT]]:
957958
level = self.level
958959
result = self._grouper.get_iterator(self._selected_obj)
959960
# mypy: Argument 1 to "len" has incompatible type "Hashable"; expected "Sized"
960-
if (
961-
(is_list_like(level) and len(level) == 1) # type: ignore[arg-type]
962-
or (isinstance(keys, list) and len(keys) == 1)
961+
if (is_list_like(level) and len(level) == 1) or ( # type: ignore[arg-type]
962+
isinstance(keys, list) and len(keys) == 1
963963
):
964964
# GH#42795 - when keys is a list, return tuples even when length is 1
965965
result = (((key,), group) for key, group in result)

pandas/core/indexing.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
from typing import (
66
TYPE_CHECKING,
77
Any,
8-
TypeVar,
98
cast,
109
final,
1110
)
@@ -83,6 +82,7 @@
8382
Axis,
8483
AxisInt,
8584
Self,
85+
T,
8686
npt,
8787
)
8888

@@ -91,7 +91,6 @@
9191
Series,
9292
)
9393

94-
T = TypeVar("T")
9594
# "null slice"
9695
_NS = slice(None, None)
9796
_one_ellipsis_message = "indexer may only contain one '...' entry"

0 commit comments

Comments
 (0)