Skip to content

Commit 4f3b32b

Browse files
PERF/TYP: typing cast in __getitem__ gives quite some overhead (#44624)
* PERF/TYP: typing cast in __getitem__ gives quite some overhead * stringify * categorical as well
1 parent 3e1cfc5 commit 4f3b32b

File tree

2 files changed

+6
-3
lines changed

2 files changed

+6
-3
lines changed

pandas/core/arrays/categorical.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -509,7 +509,7 @@ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
509509
result = self.copy() if copy else self
510510

511511
elif is_categorical_dtype(dtype):
512-
dtype = cast(Union[str, CategoricalDtype], dtype)
512+
dtype = cast("Union[str, CategoricalDtype]", dtype)
513513

514514
# GH 10696/18593/18630
515515
dtype = self.dtype.update_dtype(dtype)

pandas/core/arrays/datetimelike.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -331,10 +331,13 @@ def __getitem__(
331331
This getitem defers to the underlying array, which by-definition can
332332
only handle list-likes, slices, and integer scalars
333333
"""
334-
# Use cast as we know we will get back a DatetimeLikeArray or DTScalar
334+
# Use cast as we know we will get back a DatetimeLikeArray or DTScalar,
335+
# but skip evaluating the Union at runtime for performance
336+
# (see https://github.com/pandas-dev/pandas/pull/44624)
335337
result = cast(
336-
Union[DatetimeLikeArrayT, DTScalarOrNaT], super().__getitem__(key)
338+
"Union[DatetimeLikeArrayT, DTScalarOrNaT]", super().__getitem__(key)
337339
)
340+
result = super().__getitem__(key)
338341
if lib.is_scalar(result):
339342
return result
340343
else:

0 commit comments

Comments
 (0)