|
1 | 1 | # Arithmetic tests for DataFrame/Series/Index/Array classes that should
|
2 | 2 | # behave identically.
|
3 | 3 | # Specifically for object dtype
|
| 4 | +import datetime |
4 | 5 | from decimal import Decimal
|
5 | 6 | import operator
|
6 | 7 |
|
@@ -317,3 +318,48 @@ def test_rsub_object(self):
|
317 | 318 |
|
318 | 319 | with pytest.raises(TypeError):
|
319 | 320 | np.array([True, pd.Timestamp.now()]) - index
|
| 321 | + |
| 322 | + |
| 323 | +class MyIndex(pd.Index): |
| 324 | + # Simple index subclass that tracks ops calls. |
| 325 | + |
| 326 | + _calls: int |
| 327 | + |
| 328 | + @classmethod |
| 329 | + def _simple_new(cls, values, name=None, dtype=None): |
| 330 | + result = object.__new__(cls) |
| 331 | + result._data = values |
| 332 | + result._index_data = values |
| 333 | + result._name = name |
| 334 | + result._calls = 0 |
| 335 | + |
| 336 | + return result._reset_identity() |
| 337 | + |
| 338 | + def __add__(self, other): |
| 339 | + self._calls += 1 |
| 340 | + return self._simple_new(self._index_data) |
| 341 | + |
| 342 | + def __radd__(self, other): |
| 343 | + return self.__add__(other) |
| 344 | + |
| 345 | + |
| 346 | +@pytest.mark.parametrize( |
| 347 | + "other", |
| 348 | + [ |
| 349 | + [datetime.timedelta(1), datetime.timedelta(2)], |
| 350 | + [datetime.datetime(2000, 1, 1), datetime.datetime(2000, 1, 2)], |
| 351 | + [pd.Period("2000"), pd.Period("2001")], |
| 352 | + ["a", "b"], |
| 353 | + ], |
| 354 | + ids=["timedelta", "datetime", "period", "object"], |
| 355 | +) |
| 356 | +def test_index_ops_defer_to_unknown_subclasses(other): |
| 357 | + # https://github.com/pandas-dev/pandas/issues/31109 |
| 358 | + values = np.array( |
| 359 | + [datetime.date(2000, 1, 1), datetime.date(2000, 1, 2)], dtype=object |
| 360 | + ) |
| 361 | + a = MyIndex._simple_new(values) |
| 362 | + other = pd.Index(other) |
| 363 | + result = other + a |
| 364 | + assert isinstance(result, MyIndex) |
| 365 | + assert a._calls == 1 |
0 commit comments