diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index a5af4e727391a..3beaa2dfa788a 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -147,7 +147,7 @@ Datetimelike - Bug in :class:`Timestamp` subtraction when subtracting a :class:`Timestamp` from a ``np.datetime64`` object incorrectly raising ``TypeError`` (:issue:`28286`) - Addition and subtraction of integer or integer-dtype arrays with :class:`Timestamp` will now raise ``NullFrequencyError`` instead of ``ValueError`` (:issue:`28268`) - Bug in :class:`Series` and :class:`DataFrame` with integer dtype failing to raise ``TypeError`` when adding or subtracting a ``np.datetime64`` object (:issue:`28080`) -- +- Bug in :class:`Week` with ``weekday`` incorrectly raising ``AttributeError`` instead of ``TypeError`` when adding or subtracting an invalid type (:issue:`28530`) Timedelta diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 3ed25b8d3edd5..ddf2c6e65b474 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -4348,3 +4348,12 @@ def test_last_week_of_month_on_offset(): slow = (ts + offset) - offset == ts fast = offset.onOffset(ts) assert fast == slow + + +def test_week_add_invalid(): + # Week with weekday should raise TypeError and _not_ AttributeError + # when adding invalid offset + offset = Week(weekday=1) + other = Day() + with pytest.raises(TypeError, match="Cannot add"): + offset + other diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index dfe91b514bbe1..4491e6ad9ac7e 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -138,7 +138,7 @@ def to_offset(freq): delta = offset else: delta = delta + offset - except Exception: + except ValueError: raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(freq)) else: @@ -170,7 +170,7 @@ def to_offset(freq): delta = offset else: delta = delta + offset - except Exception: + except (ValueError, TypeError): raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(freq)) if delta is None: diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index edf58ba3850a1..82cbfa831bf32 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -605,7 +605,7 @@ def apply(self, other): return BDay(self.n, offset=self.offset + other, normalize=self.normalize) else: raise ApplyTypeError( - "Only know how to combine business day with " "datetime or timedelta." + "Only know how to combine business day with datetime or timedelta." ) @apply_index_wraps @@ -1545,6 +1545,13 @@ def apply(self, other): if self.weekday is None: return other + self.n * self._inc + if not isinstance(other, datetime): + raise TypeError( + "Cannot add {typ} to {cls}".format( + typ=type(other).__name__, cls=type(self).__name__ + ) + ) + k = self.n otherDay = other.weekday() if otherDay != self.weekday: