Skip to content

CLN: share compatibility-check code #30688

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 11 additions & 15 deletions pandas/core/arrays/period.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,12 +215,7 @@ def __init__(self, values, freq=None, dtype=None, copy=False):

if isinstance(values, type(self)):
if freq is not None and freq != values.freq:
msg = DIFFERENT_FREQ.format(
cls=type(self).__name__,
own_freq=values.freq.freqstr,
other_freq=freq.freqstr,
)
raise IncompatibleFrequency(msg)
raise raise_on_incompatible(values, freq)
values, freq = values._data, values.freq

values = np.array(values, dtype="int64", copy=copy)
Expand Down Expand Up @@ -323,7 +318,7 @@ def _check_compatible_with(self, other):
if other is NaT:
return
if self.freqstr != other.freqstr:
_raise_on_incompatible(self, other)
raise raise_on_incompatible(self, other)

# --------------------------------------------------------------------
# Data / Attributes
Expand Down Expand Up @@ -682,7 +677,7 @@ def _add_offset(self, other):
assert not isinstance(other, Tick)
base = libfrequencies.get_base_alias(other.rule_code)
if base != self.freq.rule_code:
_raise_on_incompatible(self, other)
raise raise_on_incompatible(self, other)

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

new_ordinals = super()._add_delta(other)
return type(self)(new_ordinals, freq=self.freq)
Expand Down Expand Up @@ -802,28 +797,29 @@ def _check_timedeltalike_freq_compat(self, other):
# by which will be added to self.
return delta

_raise_on_incompatible(self, other)
raise raise_on_incompatible(self, other)


PeriodArray._add_comparison_ops()


def _raise_on_incompatible(left, right):
def raise_on_incompatible(left, right):
"""
Helper function to render a consistent error message when raising
IncompatibleFrequency.

Parameters
----------
left : PeriodArray
right : DateOffset, Period, ndarray, or timedelta-like
right : None, DateOffset, Period, ndarray, or timedelta-like

Raises
Returns
------
IncompatibleFrequency
Exception to be raised by the caller.
"""
# GH#24283 error message format depends on whether right is scalar
if isinstance(right, np.ndarray):
if isinstance(right, np.ndarray) or right is None:
other_freq = None
elif isinstance(right, (ABCPeriodIndex, PeriodArray, Period, DateOffset)):
other_freq = right.freqstr
Expand All @@ -833,7 +829,7 @@ def _raise_on_incompatible(left, right):
msg = DIFFERENT_FREQ.format(
cls=type(left).__name__, own_freq=left.freqstr, other_freq=other_freq
)
raise IncompatibleFrequency(msg)
return IncompatibleFrequency(msg)


# -------------------------------------------------------------------
Expand Down
31 changes: 11 additions & 20 deletions pandas/core/indexes/period.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from pandas._libs import index as libindex
from pandas._libs.tslibs import NaT, frequencies as libfrequencies, iNaT, resolution
from pandas._libs.tslibs.period import DIFFERENT_FREQ, IncompatibleFrequency, Period
from pandas._libs.tslibs.period import Period
from pandas.util._decorators import Appender, Substitution, cache_readonly

from pandas.core.dtypes.common import (
Expand All @@ -21,7 +21,12 @@
)

from pandas.core.accessor import delegate_names
from pandas.core.arrays.period import PeriodArray, period_array, validate_dtype_freq
from pandas.core.arrays.period import (
PeriodArray,
period_array,
raise_on_incompatible,
validate_dtype_freq,
)
from pandas.core.base import _shared_docs
import pandas.core.common as com
import pandas.core.indexes.base as ibase
Expand Down Expand Up @@ -338,21 +343,15 @@ def _maybe_convert_timedelta(self, other):
if base == self.freq.rule_code:
return other.n

msg = DIFFERENT_FREQ.format(
cls=type(self).__name__, own_freq=self.freqstr, other_freq=other.freqstr
)
raise IncompatibleFrequency(msg)
raise raise_on_incompatible(self, other)
elif is_integer(other):
# integer is passed to .shift via
# _add_datetimelike_methods basically
# but ufunc may pass integer to _add_delta
return other

# raise when input doesn't have freq
msg = DIFFERENT_FREQ.format(
cls=type(self).__name__, own_freq=self.freqstr, other_freq=None
)
raise IncompatibleFrequency(msg)
raise raise_on_incompatible(self, None)

# ------------------------------------------------------------------------
# Rendering Methods
Expand Down Expand Up @@ -486,12 +485,7 @@ def astype(self, dtype, copy=True, how="start"):
def searchsorted(self, value, side="left", sorter=None):
if isinstance(value, Period):
if value.freq != self.freq:
msg = DIFFERENT_FREQ.format(
cls=type(self).__name__,
own_freq=self.freqstr,
other_freq=value.freqstr,
)
raise IncompatibleFrequency(msg)
raise raise_on_incompatible(self, value)
value = value.ordinal
elif isinstance(value, str):
try:
Expand Down Expand Up @@ -785,10 +779,7 @@ def _assert_can_do_setop(self, other):
# *Can't* use PeriodIndexes of different freqs
# *Can* use PeriodIndex/DatetimeIndex
if isinstance(other, PeriodIndex) and self.freq != other.freq:
msg = DIFFERENT_FREQ.format(
cls=type(self).__name__, own_freq=self.freqstr, other_freq=other.freqstr
)
raise IncompatibleFrequency(msg)
raise raise_on_incompatible(self, other)

def _wrap_setop_result(self, other, result):
name = get_op_result_name(self, other)
Expand Down
11 changes: 6 additions & 5 deletions pandas/tests/indexes/period/test_setops.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import numpy as np
import pytest

from pandas._libs.tslibs import IncompatibleFrequency

import pandas as pd
from pandas import Index, PeriodIndex, date_range, period_range
import pandas._testing as tm
import pandas.core.indexes.period as period


def _permute(obj):
Expand Down Expand Up @@ -177,11 +178,11 @@ def test_union_misc(self, sort):
# raise if different frequencies
index = period_range("1/1/2000", "1/20/2000", freq="D")
index2 = period_range("1/1/2000", "1/20/2000", freq="W-WED")
with pytest.raises(period.IncompatibleFrequency):
with pytest.raises(IncompatibleFrequency):
index.union(index2, sort=sort)

index3 = period_range("1/1/2000", "1/20/2000", freq="2D")
with pytest.raises(period.IncompatibleFrequency):
with pytest.raises(IncompatibleFrequency):
index.join(index3)

def test_union_dataframe_index(self):
Expand Down Expand Up @@ -213,11 +214,11 @@ def test_intersection(self, sort):
# raise if different frequencies
index = period_range("1/1/2000", "1/20/2000", freq="D")
index2 = period_range("1/1/2000", "1/20/2000", freq="W-WED")
with pytest.raises(period.IncompatibleFrequency):
with pytest.raises(IncompatibleFrequency):
index.intersection(index2, sort=sort)

index3 = period_range("1/1/2000", "1/20/2000", freq="2D")
with pytest.raises(period.IncompatibleFrequency):
with pytest.raises(IncompatibleFrequency):
index.intersection(index3, sort=sort)

@pytest.mark.parametrize("sort", [None, False])
Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/indexes/period/test_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import numpy as np
import pytest

from pandas._libs.tslibs import IncompatibleFrequency
from pandas._libs.tslibs.ccalendar import MONTHS

import pandas as pd
Expand All @@ -18,7 +19,6 @@
to_datetime,
)
import pandas._testing as tm
import pandas.core.indexes.period as period


class TestPeriodRepresentation:
Expand Down Expand Up @@ -232,11 +232,11 @@ def test_searchsorted(self, freq):
assert pidx.searchsorted(p2) == 3

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

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


Expand Down
3 changes: 2 additions & 1 deletion pandas/tests/series/test_arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
import numpy as np
import pytest

from pandas._libs.tslibs import IncompatibleFrequency

import pandas as pd
from pandas import Series
import pandas._testing as tm
from pandas.core.indexes.period import IncompatibleFrequency


def _permute(obj):
Expand Down