Skip to content

Commit c90c78d

Browse files
committed
TYPING: narrow tz-aware union path to DatetimeArray in _union to satisfy mypy; behavior unchanged (GH#62915)
1 parent e8bf47c commit c90c78d

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

pandas/core/indexes/datetimelike.py

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -737,11 +737,21 @@ def _union(self, other, sort):
737737
# local-time irregularities across DST transitions, then convert back.
738738
tz = getattr(self.dtype, "tz", None)
739739
if tz is not None:
740-
left_utc = self.tz_convert("UTC")
741-
right_utc = other.tz_convert("UTC")
742-
res_utc = super(type(left_utc), left_utc)._union(right_utc, sort)
743-
res = res_utc.tz_convert(tz)
744-
return res._with_freq("infer")
740+
# Narrow to DatetimeArray to access tz_convert without mypy errors
741+
if isinstance(self._data, DatetimeArray) and isinstance(
742+
other._data, DatetimeArray
743+
):
744+
left_utc_arr = self._data.tz_convert("UTC")
745+
right_utc_arr = other._data.tz_convert("UTC")
746+
left_utc = type(self)._simple_new(left_utc_arr, name=self.name)
747+
right_utc = type(other)._simple_new(right_utc_arr, name=other.name)
748+
res_utc = super(type(left_utc), left_utc)._union(right_utc, sort)
749+
# res_utc is DatetimeIndex; convert its underlying array back to tz
750+
res_arr = cast(DatetimeArray, res_utc._data).tz_convert(tz)
751+
res = type(self)._simple_new(res_arr, name=res_utc.name)
752+
return res._with_freq("infer")
753+
# Defensive fallback if types are unexpected
754+
return super()._union(other, sort)._with_freq("infer")
745755
return super()._union(other, sort)._with_freq("infer")
746756

747757
# --------------------------------------------------------------------

0 commit comments

Comments
 (0)