Skip to content

CLN: disallow tuple in to_offset #34703

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 7 commits into from
Jun 15, 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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -820,6 +820,7 @@ Datetimelike
- Bug in :meth:`DatetimeIndex.intersection` and :meth:`TimedeltaIndex.intersection` with results not having the correct ``name`` attribute (:issue:`33904`)
- Bug in :meth:`DatetimeArray.__setitem__`, :meth:`TimedeltaArray.__setitem__`, :meth:`PeriodArray.__setitem__` incorrectly allowing values with ``int64`` dtype to be silently cast (:issue:`33717`)
- Bug in subtracting :class:`TimedeltaIndex` from :class:`Period` incorrectly raising ``TypeError`` in some cases where it should succeed and ``IncompatibleFrequency`` in some cases where it should raise ``TypeError`` (:issue:`33883`)
- The ``freq`` keyword in :class:`Period`, :func:`date_range`, :func:`period_range`, :func:`pd.tseries.frequencies.to_offset` no longer allows tuples, pass as string instead (:issue:`34703`)

Timedelta
^^^^^^^^^
Expand Down
43 changes: 5 additions & 38 deletions pandas/_libs/tslibs/offsets.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -3482,36 +3482,6 @@ INVALID_FREQ_ERR_MSG = "Invalid frequency: {0}"
_offset_map = {}


cdef _base_and_stride(str freqstr):
"""
Return base freq and stride info from string representation

Returns
-------
base : str
stride : int

Examples
--------
_base_and_stride('5Min') -> 'Min', 5
"""
groups = opattern.match(freqstr)

if not groups:
raise ValueError(f"Could not evaluate {freqstr}")

stride = groups.group(1)

if len(stride):
stride = int(stride)
else:
stride = 1

base = groups.group(2)

return base, stride


# TODO: better name?
def _get_offset(name: str) -> BaseOffset:
"""
Expand Down Expand Up @@ -3574,10 +3544,10 @@ cpdef to_offset(freq):
>>> to_offset("1D1H")
<25 * Hours>

>>> to_offset(("W", 2))
>>> to_offset("2W")
<2 * Weeks: weekday=6>

>>> to_offset((2, "B"))
>>> to_offset("2B")
<2 * BusinessDays>

>>> to_offset(pd.Timedelta(days=1))
Expand All @@ -3593,12 +3563,9 @@ cpdef to_offset(freq):
return freq

if isinstance(freq, tuple):
name = freq[0]
stride = freq[1]
if isinstance(stride, str):
name, stride = stride, name
name, _ = _base_and_stride(name)
delta = _get_offset(name) * stride
raise TypeError(
f"to_offset does not support tuples {freq}, pass as a string instead"
)

elif isinstance(freq, timedelta):
return delta_to_tick(freq)
Expand Down
11 changes: 6 additions & 5 deletions pandas/tests/indexes/datetimes/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -946,11 +946,6 @@ def test_datetimeindex_constructor_misc(self):
assert idx[0] == sdate + 0 * offsets.BDay()
assert idx.freq == "B"

idx = date_range(end=edate, freq=("D", 5), periods=20)
assert len(idx) == 20
assert idx[-1] == edate
assert idx.freq == "5D"

idx1 = date_range(start=sdate, end=edate, freq="W-SUN")
idx2 = date_range(start=sdate, end=edate, freq=offsets.Week(weekday=6))
assert len(idx1) == len(idx2)
Expand Down Expand Up @@ -979,6 +974,12 @@ def test_pass_datetimeindex_to_index(self):

tm.assert_numpy_array_equal(idx.values, expected.values)

def test_date_range_tuple_freq_raises(self):
# GH#34703
edate = datetime(2000, 1, 1)
with pytest.raises(TypeError, match="pass as a string instead"):
date_range(end=edate, freq=("D", 5), periods=20)


def test_timestamp_constructor_invalid_fold_raise():
# Test for #25057
Expand Down
10 changes: 4 additions & 6 deletions pandas/tests/indexes/period/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -463,12 +463,6 @@ def test_constructor(self):
assert (i1 == i2).all()
assert i1.freq == i2.freq

end_intv = Period("2006-12-31", ("w", 1))
i2 = period_range(end=end_intv, periods=10)
assert len(i1) == len(i2)
assert (i1 == i2).all()
assert i1.freq == i2.freq

end_intv = Period("2005-05-01", "B")
i1 = period_range(start=start, end=end_intv)

Expand All @@ -490,6 +484,10 @@ def test_constructor(self):
with pytest.raises(IncompatibleFrequency, match=msg):
PeriodIndex(vals)

# tuple freq disallowed GH#34703
with pytest.raises(TypeError, match="pass as a string instead"):
Period("2006-12-31", ("w", 1))

@pytest.mark.parametrize(
"freq", ["M", "Q", "A", "D", "B", "T", "S", "L", "U", "N", "H"]
)
Expand Down
6 changes: 0 additions & 6 deletions pandas/tests/indexes/period/test_period.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,12 +172,6 @@ def test_period_index_length(self):
assert (i1 == i2).all()
assert i1.freq == i2.freq

end_intv = Period("2006-12-31", ("w", 1))
i2 = period_range(end=end_intv, periods=10)
assert len(i1) == len(i2)
assert (i1 == i2).all()
assert i1.freq == i2.freq

msg = "start and end must have same freq"
with pytest.raises(ValueError, match=msg):
period_range(start=start, end=end_intv)
Expand Down
6 changes: 4 additions & 2 deletions pandas/tests/scalar/period/test_period.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@ def test_construction(self):
i1 = Period("1982", freq="min")
i2 = Period("1982", freq="MIN")
assert i1 == i2
i2 = Period("1982", freq=("Min", 1))
assert i1 == i2

i1 = Period(year=2005, month=3, day=1, freq="D")
i2 = Period("3/1/2005", freq="D")
Expand Down Expand Up @@ -80,6 +78,10 @@ def test_construction(self):
with pytest.raises(ValueError, match=msg):
Period("2007-1-1", freq="X")

# GH#34703 tuple freq disallowed
with pytest.raises(TypeError, match="pass as a string instead"):
Period("1982", freq=("Min", 1))

def test_construction_bday(self):

# Biz day construction, roll forward if non-weekday
Expand Down
9 changes: 7 additions & 2 deletions pandas/tests/tslibs/test_to_offset.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
[
(to_offset("10us"), offsets.Micro(10)),
(offsets.Hour(), offsets.Hour()),
((5, "T"), offsets.Minute(5)),
("2h30min", offsets.Minute(150)),
("2h 30min", offsets.Minute(150)),
("2h30min15s", offsets.Second(150 * 60 + 15)),
Expand Down Expand Up @@ -89,10 +88,16 @@ def test_to_offset_invalid(freqstr):


def test_to_offset_no_evaluate():
with pytest.raises(ValueError, match="Could not evaluate"):
msg = str(("", ""))
with pytest.raises(TypeError, match=msg):
to_offset(("", ""))


def test_to_offset_tuple_unsupported():
with pytest.raises(TypeError, match="pass as a string instead"):
to_offset((5, "T"))


@pytest.mark.parametrize(
"freqstr,expected",
[
Expand Down