Skip to content

Commit b21cec1

Browse files
committed
CLN: frequency.get_offset always return copy
1 parent 6b8a721 commit b21cec1

File tree

4 files changed

+31
-57
lines changed

4 files changed

+31
-57
lines changed

Diff for: doc/source/whatsnew/v0.18.0.txt

+2
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,8 @@ Deprecations
252252

253253
For example, instead of ``s.rolling(window=5,freq='D').max()`` to get the max value on a rolling 5 Day window, one could use ``s.resample('D',how='max').rolling(window=5).max()``, which first resamples the data to daily data, then provides a rolling 5 day window.
254254

255+
- ``pd.tseries.frequencies.get_offset_name`` function is deprecated. Use offset's ``.freqstr`` property as alternative (:issue:`11192`)
256+
255257
.. _whatsnew_0180.prior_deprecations:
256258

257259
Removal of prior version deprecations/changes

Diff for: pandas/tseries/frequencies.py

+12-18
Original file line numberDiff line numberDiff line change
@@ -286,8 +286,7 @@ def _get_freq_str(base, mult=1):
286286
MonthEnd, BMonthBegin, BMonthEnd,
287287
QuarterBegin, QuarterEnd, BQuarterBegin,
288288
BQuarterEnd, YearBegin, YearEnd,
289-
BYearBegin, BYearEnd, _make_offset
290-
)
289+
BYearBegin, BYearEnd, prefix_mapping)
291290
try:
292291
cday = CDay()
293292
except NotImplementedError:
@@ -547,13 +546,17 @@ def get_offset(name):
547546

548547
if name not in _offset_map:
549548
try:
550-
# generate and cache offset
551-
offset = _make_offset(name)
549+
split = name.split('-')
550+
klass = prefix_mapping[split[0]]
551+
# handles case where there's no suffix (and will TypeError if too many '-')
552+
offset = klass._from_name(*split[1:])
552553
except (ValueError, TypeError, KeyError):
553554
# bad prefix or suffix
554555
raise ValueError('Bad rule name requested: %s.' % name)
556+
# cache
555557
_offset_map[name] = offset
556-
return _offset_map[name]
558+
# do not return cache because it's mutable
559+
return _offset_map[name].copy()
557560

558561

559562
getOffset = get_offset
@@ -567,19 +570,10 @@ def get_offset_name(offset):
567570
--------
568571
get_offset_name(BMonthEnd(1)) --> 'EOM'
569572
"""
570-
if offset is None:
571-
raise ValueError("Offset can't be none!")
572-
# Hack because this is what it did before...
573-
if isinstance(offset, BDay):
574-
if offset.n != 1:
575-
raise ValueError('Bad rule given: %s.' % 'BusinessDays')
576-
else:
577-
return offset.rule_code
578-
try:
579-
return offset.freqstr
580-
except AttributeError:
581-
# Bad offset, give useful error.
582-
raise ValueError('Bad rule given: %s.' % offset)
573+
574+
msg = "get_offset_name(offset) is deprecated. Use offset.freqstr instead"
575+
warnings.warn(msg, FutureWarning, stacklevel=2)
576+
return offset.freqstr
583577

584578

585579
def get_legacy_offset_name(offset):

Diff for: pandas/tseries/offsets.py

+1-21
Original file line numberDiff line numberDiff line change
@@ -309,8 +309,6 @@ def _params(self):
309309
return params
310310

311311
def __repr__(self):
312-
if hasattr(self, '_named'):
313-
return self._named
314312
className = getattr(self, '_outputName', type(self).__name__)
315313
exclude = set(['n', 'inc', 'normalize'])
316314
attrs = []
@@ -346,10 +344,7 @@ def __repr__(self):
346344

347345
@property
348346
def name(self):
349-
if hasattr(self, '_named'):
350-
return self._named
351-
else:
352-
return self.rule_code
347+
return self.rule_code
353348

354349
def __eq__(self, other):
355350
if other is None:
@@ -516,8 +511,6 @@ class BusinessMixin(object):
516511
# attributes on each object rather than the existing behavior of iterating
517512
# over internal ``__dict__``
518513
def __repr__(self):
519-
if hasattr(self, '_named'):
520-
return self._named
521514
className = getattr(self, '_outputName', self.__class__.__name__)
522515

523516
if abs(self.n) != 1:
@@ -2668,16 +2661,3 @@ def generate_range(start=None, end=None, periods=None,
26682661
])
26692662

26702663
prefix_mapping['N'] = Nano
2671-
2672-
def _make_offset(key):
2673-
"""Gets offset based on key. KeyError if prefix is bad, ValueError if
2674-
suffix is bad. All handled by `get_offset` in tseries/frequencies. Not
2675-
public."""
2676-
if key is None:
2677-
return None
2678-
split = key.split('-')
2679-
klass = prefix_mapping[split[0]]
2680-
# handles case where there's no suffix (and will TypeError if too many '-')
2681-
obj = klass._from_name(*split[1:])
2682-
obj._named = key
2683-
return obj

Diff for: pandas/tseries/tests/test_offsets.py

+16-18
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
QuarterBegin, BQuarterBegin, BMonthBegin, DateOffset, Week,
1717
YearBegin, YearEnd, Hour, Minute, Second, Day, Micro, Milli, Nano, Easter,
1818
WeekOfMonth, format, ole2datetime, QuarterEnd, to_datetime, normalize_date,
19-
get_offset, get_offset_name, get_standard_freq)
19+
get_offset, get_standard_freq)
2020

2121
from pandas import Series
2222
from pandas.tseries.frequencies import _offset_map, get_freq_code, _get_freq_str
@@ -3593,19 +3593,20 @@ def test_compare_ticks(self):
35933593

35943594
class TestOffsetNames(tm.TestCase):
35953595
def test_get_offset_name(self):
3596-
assertRaisesRegexp(ValueError, 'Bad rule.*BusinessDays', get_offset_name, BDay(2))
3597-
3598-
assert get_offset_name(BDay()) == 'B'
3599-
assert get_offset_name(BMonthEnd()) == 'BM'
3600-
assert get_offset_name(Week(weekday=0)) == 'W-MON'
3601-
assert get_offset_name(Week(weekday=1)) == 'W-TUE'
3602-
assert get_offset_name(Week(weekday=2)) == 'W-WED'
3603-
assert get_offset_name(Week(weekday=3)) == 'W-THU'
3604-
assert get_offset_name(Week(weekday=4)) == 'W-FRI'
3605-
3606-
self.assertEqual(get_offset_name(LastWeekOfMonth(weekday=WeekDay.SUN)), "LWOM-SUN")
3607-
self.assertEqual(get_offset_name(makeFY5253LastOfMonthQuarter(weekday=1, startingMonth=3, qtr_with_extra_week=4)),"REQ-L-MAR-TUE-4")
3608-
self.assertEqual(get_offset_name(makeFY5253NearestEndMonthQuarter(weekday=1, startingMonth=3, qtr_with_extra_week=3)), "REQ-N-MAR-TUE-3")
3596+
self.assertEqual(BDay().freqstr, 'B')
3597+
self.assertEqual(BDay(2).freqstr, '2B')
3598+
self.assertEqual(BMonthEnd().freqstr, 'BM')
3599+
self.assertEqual(Week(weekday=0).freqstr, 'W-MON')
3600+
self.assertEqual(Week(weekday=1).freqstr, 'W-TUE')
3601+
self.assertEqual(Week(weekday=2).freqstr, 'W-WED')
3602+
self.assertEqual(Week(weekday=3).freqstr, 'W-THU')
3603+
self.assertEqual(Week(weekday=4).freqstr, 'W-FRI')
3604+
3605+
self.assertEqual(LastWeekOfMonth(weekday=WeekDay.SUN).freqstr, "LWOM-SUN")
3606+
self.assertEqual(makeFY5253LastOfMonthQuarter(weekday=1, startingMonth=3, qtr_with_extra_week=4).freqstr,
3607+
"REQ-L-MAR-TUE-4")
3608+
self.assertEqual(makeFY5253NearestEndMonthQuarter(weekday=1, startingMonth=3, qtr_with_extra_week=3).freqstr,
3609+
"REQ-N-MAR-TUE-3")
36093610

36103611
def test_get_offset():
36113612
assertRaisesRegexp(ValueError, "rule.*GIBBERISH", get_offset, 'gibberish')
@@ -3834,13 +3835,10 @@ def test_str_for_named_is_name(self):
38343835
names += ['W-' + day for day in days]
38353836
names += ['WOM-' + week + day for week in ('1', '2', '3', '4')
38363837
for day in days]
3837-
#singletons
3838-
names += ['S', 'T', 'U', 'BM', 'BMS', 'BQ', 'QS'] # No 'Q'
38393838
_offset_map.clear()
38403839
for name in names:
38413840
offset = get_offset(name)
3842-
self.assertEqual(repr(offset), name)
3843-
self.assertEqual(str(offset), name)
3841+
self.assertEqual(offset.freqstr, name)
38443842

38453843

38463844
def get_utc_offset_hours(ts):

0 commit comments

Comments
 (0)