Skip to content

Commit 97c8c18

Browse files
Switch .dt to raise an AttributeError (#8724)
* Switch `.dt` to raise an `AttributeError` Discussion at #8718 * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent db680b0 commit 97c8c18

File tree

3 files changed

+10
-3
lines changed

3 files changed

+10
-3
lines changed

doc/whats-new.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,9 @@ Documentation
8282
Internal Changes
8383
~~~~~~~~~~~~~~~~
8484

85+
- ``DataArray.dt`` now raises an ``AttributeError`` rather than a ``TypeError``
86+
when the data isn't datetime-like. (:issue:`8718`, :pull:`8724`)
87+
By `Maximilian Roos <https://github.com/max-sixty>`_.
8588

8689
.. _whats-new.2024.01.1:
8790

xarray/core/accessor_dt.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -616,7 +616,11 @@ def __new__(cls, obj: T_DataArray) -> CombinedDatetimelikeAccessor:
616616
# appropriate. Since we're checking the dtypes anyway, we'll just
617617
# do all the validation here.
618618
if not _contains_datetime_like_objects(obj.variable):
619-
raise TypeError(
619+
# We use an AttributeError here so that `obj.dt` raises an error that
620+
# `getattr` expects; https://github.com/pydata/xarray/issues/8718. It's a
621+
# bit unusual in a `__new__`, but that's the only case where we use this
622+
# class.
623+
raise AttributeError(
620624
"'.dt' accessor only available for "
621625
"DataArray with datetime64 timedelta64 dtype or "
622626
"for arrays containing cftime datetime "

xarray/tests/test_accessor_dt.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ def test_not_datetime_type(self) -> None:
145145
nontime_data = self.data.copy()
146146
int_data = np.arange(len(self.data.time)).astype("int8")
147147
nontime_data = nontime_data.assign_coords(time=int_data)
148-
with pytest.raises(TypeError, match=r"dt"):
148+
with pytest.raises(AttributeError, match=r"dt"):
149149
nontime_data.time.dt
150150

151151
@pytest.mark.filterwarnings("ignore:dt.weekofyear and dt.week have been deprecated")
@@ -310,7 +310,7 @@ def test_not_datetime_type(self) -> None:
310310
nontime_data = self.data.copy()
311311
int_data = np.arange(len(self.data.time)).astype("int8")
312312
nontime_data = nontime_data.assign_coords(time=int_data)
313-
with pytest.raises(TypeError, match=r"dt"):
313+
with pytest.raises(AttributeError, match=r"dt"):
314314
nontime_data.time.dt
315315

316316
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)