Skip to content

Commit d5d9d79

Browse files
jbrockmendeljreback
authored andcommitted
REF: share compatibility-raising code (#30688)
1 parent 6f690b0 commit d5d9d79

File tree

5 files changed

+33
-44
lines changed

5 files changed

+33
-44
lines changed

pandas/core/arrays/period.py

+11-15
Original file line numberDiff line numberDiff line change
@@ -215,12 +215,7 @@ def __init__(self, values, freq=None, dtype=None, copy=False):
215215

216216
if isinstance(values, type(self)):
217217
if freq is not None and freq != values.freq:
218-
msg = DIFFERENT_FREQ.format(
219-
cls=type(self).__name__,
220-
own_freq=values.freq.freqstr,
221-
other_freq=freq.freqstr,
222-
)
223-
raise IncompatibleFrequency(msg)
218+
raise raise_on_incompatible(values, freq)
224219
values, freq = values._data, values.freq
225220

226221
values = np.array(values, dtype="int64", copy=copy)
@@ -323,7 +318,7 @@ def _check_compatible_with(self, other):
323318
if other is NaT:
324319
return
325320
if self.freqstr != other.freqstr:
326-
_raise_on_incompatible(self, other)
321+
raise raise_on_incompatible(self, other)
327322

328323
# --------------------------------------------------------------------
329324
# Data / Attributes
@@ -682,7 +677,7 @@ def _add_offset(self, other):
682677
assert not isinstance(other, Tick)
683678
base = libfrequencies.get_base_alias(other.rule_code)
684679
if base != self.freq.rule_code:
685-
_raise_on_incompatible(self, other)
680+
raise raise_on_incompatible(self, other)
686681

687682
# Note: when calling parent class's _add_timedeltalike_scalar,
688683
# it will call delta_to_nanoseconds(delta). Because delta here
@@ -750,7 +745,7 @@ def _add_delta(self, other):
750745
"""
751746
if not isinstance(self.freq, Tick):
752747
# We cannot add timedelta-like to non-tick PeriodArray
753-
_raise_on_incompatible(self, other)
748+
raise raise_on_incompatible(self, other)
754749

755750
new_ordinals = super()._add_delta(other)
756751
return type(self)(new_ordinals, freq=self.freq)
@@ -802,28 +797,29 @@ def _check_timedeltalike_freq_compat(self, other):
802797
# by which will be added to self.
803798
return delta
804799

805-
_raise_on_incompatible(self, other)
800+
raise raise_on_incompatible(self, other)
806801

807802

808803
PeriodArray._add_comparison_ops()
809804

810805

811-
def _raise_on_incompatible(left, right):
806+
def raise_on_incompatible(left, right):
812807
"""
813808
Helper function to render a consistent error message when raising
814809
IncompatibleFrequency.
815810
816811
Parameters
817812
----------
818813
left : PeriodArray
819-
right : DateOffset, Period, ndarray, or timedelta-like
814+
right : None, DateOffset, Period, ndarray, or timedelta-like
820815
821-
Raises
816+
Returns
822817
------
823818
IncompatibleFrequency
819+
Exception to be raised by the caller.
824820
"""
825821
# GH#24283 error message format depends on whether right is scalar
826-
if isinstance(right, np.ndarray):
822+
if isinstance(right, np.ndarray) or right is None:
827823
other_freq = None
828824
elif isinstance(right, (ABCPeriodIndex, PeriodArray, Period, DateOffset)):
829825
other_freq = right.freqstr
@@ -833,7 +829,7 @@ def _raise_on_incompatible(left, right):
833829
msg = DIFFERENT_FREQ.format(
834830
cls=type(left).__name__, own_freq=left.freqstr, other_freq=other_freq
835831
)
836-
raise IncompatibleFrequency(msg)
832+
return IncompatibleFrequency(msg)
837833

838834

839835
# -------------------------------------------------------------------

pandas/core/indexes/period.py

+11-20
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
from pandas._libs import index as libindex
77
from pandas._libs.tslibs import NaT, frequencies as libfrequencies, iNaT, resolution
8-
from pandas._libs.tslibs.period import DIFFERENT_FREQ, IncompatibleFrequency, Period
8+
from pandas._libs.tslibs.period import Period
99
from pandas.util._decorators import Appender, Substitution, cache_readonly
1010

1111
from pandas.core.dtypes.common import (
@@ -21,7 +21,12 @@
2121
)
2222

2323
from pandas.core.accessor import delegate_names
24-
from pandas.core.arrays.period import PeriodArray, period_array, validate_dtype_freq
24+
from pandas.core.arrays.period import (
25+
PeriodArray,
26+
period_array,
27+
raise_on_incompatible,
28+
validate_dtype_freq,
29+
)
2530
from pandas.core.base import _shared_docs
2631
import pandas.core.common as com
2732
import pandas.core.indexes.base as ibase
@@ -338,21 +343,15 @@ def _maybe_convert_timedelta(self, other):
338343
if base == self.freq.rule_code:
339344
return other.n
340345

341-
msg = DIFFERENT_FREQ.format(
342-
cls=type(self).__name__, own_freq=self.freqstr, other_freq=other.freqstr
343-
)
344-
raise IncompatibleFrequency(msg)
346+
raise raise_on_incompatible(self, other)
345347
elif is_integer(other):
346348
# integer is passed to .shift via
347349
# _add_datetimelike_methods basically
348350
# but ufunc may pass integer to _add_delta
349351
return other
350352

351353
# raise when input doesn't have freq
352-
msg = DIFFERENT_FREQ.format(
353-
cls=type(self).__name__, own_freq=self.freqstr, other_freq=None
354-
)
355-
raise IncompatibleFrequency(msg)
354+
raise raise_on_incompatible(self, None)
356355

357356
# ------------------------------------------------------------------------
358357
# Rendering Methods
@@ -486,12 +485,7 @@ def astype(self, dtype, copy=True, how="start"):
486485
def searchsorted(self, value, side="left", sorter=None):
487486
if isinstance(value, Period):
488487
if value.freq != self.freq:
489-
msg = DIFFERENT_FREQ.format(
490-
cls=type(self).__name__,
491-
own_freq=self.freqstr,
492-
other_freq=value.freqstr,
493-
)
494-
raise IncompatibleFrequency(msg)
488+
raise raise_on_incompatible(self, value)
495489
value = value.ordinal
496490
elif isinstance(value, str):
497491
try:
@@ -785,10 +779,7 @@ def _assert_can_do_setop(self, other):
785779
# *Can't* use PeriodIndexes of different freqs
786780
# *Can* use PeriodIndex/DatetimeIndex
787781
if isinstance(other, PeriodIndex) and self.freq != other.freq:
788-
msg = DIFFERENT_FREQ.format(
789-
cls=type(self).__name__, own_freq=self.freqstr, other_freq=other.freqstr
790-
)
791-
raise IncompatibleFrequency(msg)
782+
raise raise_on_incompatible(self, other)
792783

793784
def _wrap_setop_result(self, other, result):
794785
name = get_op_result_name(self, other)

pandas/tests/indexes/period/test_setops.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import numpy as np
22
import pytest
33

4+
from pandas._libs.tslibs import IncompatibleFrequency
5+
46
import pandas as pd
57
from pandas import Index, PeriodIndex, date_range, period_range
68
import pandas._testing as tm
7-
import pandas.core.indexes.period as period
89

910

1011
def _permute(obj):
@@ -177,11 +178,11 @@ def test_union_misc(self, sort):
177178
# raise if different frequencies
178179
index = period_range("1/1/2000", "1/20/2000", freq="D")
179180
index2 = period_range("1/1/2000", "1/20/2000", freq="W-WED")
180-
with pytest.raises(period.IncompatibleFrequency):
181+
with pytest.raises(IncompatibleFrequency):
181182
index.union(index2, sort=sort)
182183

183184
index3 = period_range("1/1/2000", "1/20/2000", freq="2D")
184-
with pytest.raises(period.IncompatibleFrequency):
185+
with pytest.raises(IncompatibleFrequency):
185186
index.join(index3)
186187

187188
def test_union_dataframe_index(self):
@@ -213,11 +214,11 @@ def test_intersection(self, sort):
213214
# raise if different frequencies
214215
index = period_range("1/1/2000", "1/20/2000", freq="D")
215216
index2 = period_range("1/1/2000", "1/20/2000", freq="W-WED")
216-
with pytest.raises(period.IncompatibleFrequency):
217+
with pytest.raises(IncompatibleFrequency):
217218
index.intersection(index2, sort=sort)
218219

219220
index3 = period_range("1/1/2000", "1/20/2000", freq="2D")
220-
with pytest.raises(period.IncompatibleFrequency):
221+
with pytest.raises(IncompatibleFrequency):
221222
index.intersection(index3, sort=sort)
222223

223224
@pytest.mark.parametrize("sort", [None, False])

pandas/tests/indexes/period/test_tools.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import numpy as np
44
import pytest
55

6+
from pandas._libs.tslibs import IncompatibleFrequency
67
from pandas._libs.tslibs.ccalendar import MONTHS
78

89
import pandas as pd
@@ -18,7 +19,6 @@
1819
to_datetime,
1920
)
2021
import pandas._testing as tm
21-
import pandas.core.indexes.period as period
2222

2323

2424
class TestPeriodRepresentation:
@@ -232,11 +232,11 @@ def test_searchsorted(self, freq):
232232
assert pidx.searchsorted(p2) == 3
233233

234234
msg = "Input has different freq=H from PeriodIndex"
235-
with pytest.raises(period.IncompatibleFrequency, match=msg):
235+
with pytest.raises(IncompatibleFrequency, match=msg):
236236
pidx.searchsorted(pd.Period("2014-01-01", freq="H"))
237237

238238
msg = "Input has different freq=5D from PeriodIndex"
239-
with pytest.raises(period.IncompatibleFrequency, match=msg):
239+
with pytest.raises(IncompatibleFrequency, match=msg):
240240
pidx.searchsorted(pd.Period("2014-01-01", freq="5D"))
241241

242242

pandas/tests/series/test_arithmetic.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33
import numpy as np
44
import pytest
55

6+
from pandas._libs.tslibs import IncompatibleFrequency
7+
68
import pandas as pd
79
from pandas import Series
810
import pandas._testing as tm
9-
from pandas.core.indexes.period import IncompatibleFrequency
1011

1112

1213
def _permute(obj):

0 commit comments

Comments
 (0)