Skip to content

Commit cdea41e

Browse files
authored
add Tick, BaseOffset to tslibs namespace (#34963)
1 parent 6a6faf5 commit cdea41e

File tree

14 files changed

+38
-49
lines changed

14 files changed

+38
-49
lines changed

pandas/_libs/tslibs/__init__.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,15 @@
1616
"Timestamp",
1717
"tz_convert_single",
1818
"to_offset",
19+
"Tick",
20+
"BaseOffset",
1921
]
2022

2123
from . import dtypes
2224
from .conversion import localize_pydatetime
2325
from .nattype import NaT, NaTType, iNaT, is_null_datetimelike, nat_strings
2426
from .np_datetime import OutOfBoundsDatetime
25-
from .offsets import to_offset
27+
from .offsets import BaseOffset, Tick, to_offset
2628
from .period import IncompatibleFrequency, Period
2729
from .resolution import Resolution
2830
from .timedeltas import Timedelta, delta_to_nanoseconds, ints_to_pytimedelta

pandas/compat/pickle_compat.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@
99
from typing import TYPE_CHECKING, Optional
1010
import warnings
1111

12-
from pandas import Index
12+
from pandas._libs.tslibs import BaseOffset
1313

14-
from pandas.tseries.offsets import DateOffset
14+
from pandas import Index
1515

1616
if TYPE_CHECKING:
1717
from pandas import Series, DataFrame
@@ -42,7 +42,7 @@ def load_reduce(self):
4242
return
4343
except TypeError:
4444
pass
45-
elif args and issubclass(args[0], DateOffset):
45+
elif args and issubclass(args[0], BaseOffset):
4646
# TypeError: object.__new__(Day) is not safe, use Day.__new__()
4747
cls = args[0]
4848
stack[-1] = cls.__new__(*args)

pandas/core/arrays/_ranges.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,14 @@
77

88
import numpy as np
99

10-
from pandas._libs.tslibs import OutOfBoundsDatetime, Timedelta, Timestamp
11-
12-
from pandas.tseries.offsets import DateOffset
10+
from pandas._libs.tslibs import BaseOffset, OutOfBoundsDatetime, Timedelta, Timestamp
1311

1412

1513
def generate_regular_range(
1614
start: Union[Timestamp, Timedelta],
1715
end: Union[Timestamp, Timedelta],
1816
periods: int,
19-
freq: DateOffset,
17+
freq: BaseOffset,
2018
):
2119
"""
2220
Generate a range of dates or timestamps with the spans between dates

pandas/core/arrays/datetimelike.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,12 @@
77

88
from pandas._libs import algos, lib
99
from pandas._libs.tslibs import (
10+
BaseOffset,
1011
NaT,
1112
NaTType,
1213
Period,
1314
Resolution,
15+
Tick,
1416
Timestamp,
1517
delta_to_nanoseconds,
1618
iNaT,
@@ -62,7 +64,6 @@
6264
from pandas.core.ops.invalid import invalid_comparison, make_invalid_op
6365

6466
from pandas.tseries import frequencies
65-
from pandas.tseries.offsets import DateOffset, Tick
6667

6768
DTScalarOrNaT = Union[DatetimeLikeScalar, NaTType]
6869

@@ -421,7 +422,7 @@ def _with_freq(self, freq):
421422
if freq is None:
422423
# Always valid
423424
pass
424-
elif len(self) == 0 and isinstance(freq, DateOffset):
425+
elif len(self) == 0 and isinstance(freq, BaseOffset):
425426
# Always valid. In the TimedeltaArray case, we assume this
426427
# is a Tick offset.
427428
pass
@@ -1398,7 +1399,7 @@ def __add__(self, other):
13981399
result = self._add_nat()
13991400
elif isinstance(other, (Tick, timedelta, np.timedelta64)):
14001401
result = self._add_timedeltalike_scalar(other)
1401-
elif isinstance(other, DateOffset):
1402+
elif isinstance(other, BaseOffset):
14021403
# specifically _not_ a Tick
14031404
result = self._add_offset(other)
14041405
elif isinstance(other, (datetime, np.datetime64)):
@@ -1454,7 +1455,7 @@ def __sub__(self, other):
14541455
result = self._sub_nat()
14551456
elif isinstance(other, (Tick, timedelta, np.timedelta64)):
14561457
result = self._add_timedeltalike_scalar(-other)
1457-
elif isinstance(other, DateOffset):
1458+
elif isinstance(other, BaseOffset):
14581459
# specifically _not_ a Tick
14591460
result = self._add_offset(-other)
14601461
elif isinstance(other, (datetime, np.datetime64)):
@@ -1778,7 +1779,7 @@ def maybe_infer_freq(freq):
17781779
Whether we should inherit the freq of passed data.
17791780
"""
17801781
freq_infer = False
1781-
if not isinstance(freq, DateOffset):
1782+
if not isinstance(freq, BaseOffset):
17821783
# if a passed freq is None, don't infer automatically
17831784
if freq != "infer":
17841785
freq = to_offset(freq)

pandas/core/arrays/period.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import numpy as np
66

77
from pandas._libs.tslibs import (
8+
BaseOffset,
89
NaT,
910
NaTType,
1011
Timedelta,
@@ -48,8 +49,6 @@
4849
from pandas.core.arrays import datetimelike as dtl
4950
import pandas.core.common as com
5051

51-
from pandas.tseries.offsets import DateOffset
52-
5352

5453
def _field_accessor(name: str, docstring=None):
5554
def f(self):
@@ -280,7 +279,7 @@ def dtype(self) -> PeriodDtype:
280279

281280
# error: Read-only property cannot override read-write property [misc]
282281
@property # type: ignore
283-
def freq(self) -> DateOffset:
282+
def freq(self) -> BaseOffset:
284283
"""
285284
Return the frequency object for this PeriodArray.
286285
"""
@@ -656,7 +655,7 @@ def _addsub_int_array(
656655
res_values[self._isnan] = iNaT
657656
return type(self)(res_values, freq=self.freq)
658657

659-
def _add_offset(self, other: DateOffset):
658+
def _add_offset(self, other: BaseOffset):
660659
assert not isinstance(other, Tick)
661660

662661
if other.base != self.freq.base:
@@ -784,7 +783,7 @@ def raise_on_incompatible(left, right):
784783
# GH#24283 error message format depends on whether right is scalar
785784
if isinstance(right, (np.ndarray, ABCTimedeltaArray)) or right is None:
786785
other_freq = None
787-
elif isinstance(right, (ABCPeriodIndex, PeriodArray, Period, DateOffset)):
786+
elif isinstance(right, (ABCPeriodIndex, PeriodArray, Period, BaseOffset)):
788787
other_freq = right.freqstr
789788
else:
790789
other_freq = delta_to_tick(Timedelta(right)).freqstr

pandas/core/arrays/timedeltas.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import numpy as np
55

66
from pandas._libs import lib, tslibs
7-
from pandas._libs.tslibs import NaT, Period, Timedelta, Timestamp, iNaT, to_offset
7+
from pandas._libs.tslibs import NaT, Period, Tick, Timedelta, Timestamp, iNaT, to_offset
88
from pandas._libs.tslibs.conversion import precision_from_unit
99
from pandas._libs.tslibs.fields import get_timedelta_field
1010
from pandas._libs.tslibs.timedeltas import array_to_timedelta64, parse_timedelta_unit
@@ -35,8 +35,6 @@
3535
from pandas.core.construction import extract_array
3636
from pandas.core.ops.common import unpack_zerodim_and_defer
3737

38-
from pandas.tseries.offsets import Tick
39-
4038

4139
def _field_accessor(name, alias, docstring=None):
4240
def f(self):

pandas/core/generic.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
from pandas._config import config
3232

3333
from pandas._libs import lib
34-
from pandas._libs.tslibs import Timestamp, to_offset
34+
from pandas._libs.tslibs import Tick, Timestamp, to_offset
3535
from pandas._typing import (
3636
Axis,
3737
FilePathOrBuffer,
@@ -101,7 +101,6 @@
101101
from pandas.io.formats import format as fmt
102102
from pandas.io.formats.format import DataFrameFormatter, format_percentiles
103103
from pandas.io.formats.printing import pprint_thing
104-
from pandas.tseries.offsets import Tick
105104

106105
if TYPE_CHECKING:
107106
from pandas.core.resample import Resampler

pandas/core/indexes/datetimelike.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import numpy as np
88

99
from pandas._libs import NaT, Timedelta, iNaT, join as libjoin, lib
10-
from pandas._libs.tslibs import Resolution, timezones
10+
from pandas._libs.tslibs import BaseOffset, Resolution, Tick, timezones
1111
from pandas._libs.tslibs.parsing import DateParseError
1212
from pandas._typing import Label
1313
from pandas.compat.numpy import function as nv
@@ -44,8 +44,6 @@
4444
from pandas.core.sorting import ensure_key_mapped
4545
from pandas.core.tools.timedeltas import to_timedelta
4646

47-
from pandas.tseries.offsets import DateOffset, Tick
48-
4947
_index_doc_kwargs = dict(ibase._index_doc_kwargs)
5048

5149
_T = TypeVar("_T", bound="DatetimeIndexOpsMixin")
@@ -91,7 +89,7 @@ class DatetimeIndexOpsMixin(ExtensionIndex):
9189
"""
9290

9391
_data: Union[DatetimeArray, TimedeltaArray, PeriodArray]
94-
freq: Optional[DateOffset]
92+
freq: Optional[BaseOffset]
9593
freqstr: Optional[str]
9694
_resolution_obj: Resolution
9795
_bool_ops: List[str] = []

pandas/core/indexes/interval.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
from pandas._libs import lib
1111
from pandas._libs.interval import Interval, IntervalMixin, IntervalTree
12-
from pandas._libs.tslibs import Timedelta, Timestamp, to_offset
12+
from pandas._libs.tslibs import BaseOffset, Timedelta, Timestamp, to_offset
1313
from pandas._typing import AnyArrayLike, Label
1414
from pandas.errors import InvalidIndexError
1515
from pandas.util._decorators import Appender, Substitution, cache_readonly
@@ -56,8 +56,6 @@
5656
from pandas.core.indexes.timedeltas import TimedeltaIndex, timedelta_range
5757
from pandas.core.ops import get_op_result_name
5858

59-
from pandas.tseries.offsets import DateOffset
60-
6159
_VALID_CLOSED = {"left", "right", "both", "neither"}
6260
_index_doc_kwargs = dict(ibase._index_doc_kwargs)
6361

@@ -1161,8 +1159,8 @@ def _is_type_compatible(a, b) -> bool:
11611159
"""
11621160
Helper for interval_range to check type compat of start/end/freq.
11631161
"""
1164-
is_ts_compat = lambda x: isinstance(x, (Timestamp, DateOffset))
1165-
is_td_compat = lambda x: isinstance(x, (Timedelta, DateOffset))
1162+
is_ts_compat = lambda x: isinstance(x, (Timestamp, BaseOffset))
1163+
is_td_compat = lambda x: isinstance(x, (Timedelta, BaseOffset))
11661164
return (
11671165
(is_number(a) and is_number(b))
11681166
or (is_ts_compat(a) and is_ts_compat(b))

pandas/core/indexes/period.py

+3-5
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.lib import no_default
8-
from pandas._libs.tslibs import Period, Resolution
8+
from pandas._libs.tslibs import BaseOffset, Period, Resolution, Tick
99
from pandas._libs.tslibs.parsing import DateParseError, parse_time_string
1010
from pandas._typing import DtypeObj, Label
1111
from pandas.errors import InvalidIndexError
@@ -43,8 +43,6 @@
4343
from pandas.core.indexes.numeric import Int64Index
4444
from pandas.core.ops import get_op_result_name
4545

46-
from pandas.tseries.offsets import DateOffset, Tick
47-
4846
_index_doc_kwargs = dict(ibase._index_doc_kwargs)
4947
_index_doc_kwargs.update(dict(target_klass="PeriodIndex or list of Periods"))
5048

@@ -145,7 +143,7 @@ class PeriodIndex(DatetimeIndexOpsMixin, Int64Index):
145143
_is_numeric_dtype = False
146144

147145
_data: PeriodArray
148-
freq: DateOffset
146+
freq: BaseOffset
149147

150148
_engine_type = libindex.PeriodEngine
151149
_supports_partial_string_indexing = True
@@ -287,7 +285,7 @@ def _maybe_convert_timedelta(self, other):
287285
# _check_timedeltalike_freq_compat will raise if incompatible
288286
delta = self._data._check_timedeltalike_freq_compat(other)
289287
return delta
290-
elif isinstance(other, DateOffset):
288+
elif isinstance(other, BaseOffset):
291289
if other.base == self.freq.base:
292290
return other.n
293291

pandas/core/window/rolling.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
import numpy as np
1212

13-
from pandas._libs.tslibs import to_offset
13+
from pandas._libs.tslibs import BaseOffset, to_offset
1414
import pandas._libs.window.aggregations as window_aggregations
1515
from pandas._typing import Axis, FrameOrSeries, Scalar
1616
from pandas.compat._optional import import_optional_dependency
@@ -55,8 +55,6 @@
5555
)
5656
from pandas.core.window.numba_ import generate_numba_apply_func
5757

58-
from pandas.tseries.offsets import DateOffset
59-
6058

6159
def calculate_center_offset(window) -> int:
6260
"""
@@ -1935,7 +1933,7 @@ def validate(self):
19351933

19361934
# we allow rolling on a datetimelike index
19371935
if (self.obj.empty or self.is_datetimelike) and isinstance(
1938-
self.window, (str, DateOffset, timedelta)
1936+
self.window, (str, BaseOffset, timedelta)
19391937
):
19401938

19411939
self._validate_monotonic()

pandas/plotting/_matplotlib/timeseries.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import numpy as np
77

8-
from pandas._libs.tslibs import Period, to_offset
8+
from pandas._libs.tslibs import BaseOffset, Period, to_offset
99
from pandas._libs.tslibs.dtypes import FreqGroup
1010
from pandas._typing import FrameOrSeriesUnion
1111

@@ -22,7 +22,6 @@
2222
TimeSeries_TimedeltaFormatter,
2323
)
2424
from pandas.tseries.frequencies import get_period_alias, is_subperiod, is_superperiod
25-
from pandas.tseries.offsets import DateOffset
2625

2726
if TYPE_CHECKING:
2827
from pandas import Series, Index # noqa:F401
@@ -218,7 +217,7 @@ def _use_dynamic_x(ax, data: "FrameOrSeriesUnion") -> bool:
218217
return True
219218

220219

221-
def _get_index_freq(index: "Index") -> Optional[DateOffset]:
220+
def _get_index_freq(index: "Index") -> Optional[BaseOffset]:
222221
freq = getattr(index, "freq", None)
223222
if freq is None:
224223
freq = getattr(index, "inferred_freq", None)

pandas/tests/plotting/test_datetimelike.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,17 @@
66
import numpy as np
77
import pytest
88

9-
from pandas._libs.tslibs import to_offset
9+
from pandas._libs.tslibs import BaseOffset, to_offset
1010
import pandas.util._test_decorators as td
1111

1212
from pandas import DataFrame, Index, NaT, Series, isna
1313
import pandas._testing as tm
14-
from pandas.core.indexes.datetimes import bdate_range, date_range
14+
from pandas.core.indexes.datetimes import DatetimeIndex, bdate_range, date_range
1515
from pandas.core.indexes.period import Period, PeriodIndex, period_range
1616
from pandas.core.indexes.timedeltas import timedelta_range
17-
from pandas.core.resample import DatetimeIndex
1817
from pandas.tests.plotting.common import TestPlotBase
1918

20-
from pandas.tseries.offsets import DateOffset, WeekOfMonth
19+
from pandas.tseries.offsets import WeekOfMonth
2120

2221

2322
@td.skip_if_no_mpl
@@ -1509,7 +1508,7 @@ def _check_plot_works(f, freq=None, series=None, *args, **kwargs):
15091508
ax = kwargs.pop("ax", plt.gca())
15101509
if series is not None:
15111510
dfreq = series.index.freq
1512-
if isinstance(dfreq, DateOffset):
1511+
if isinstance(dfreq, BaseOffset):
15131512
dfreq = dfreq.rule_code
15141513
if orig_axfreq is None:
15151514
assert ax.freq == dfreq

pandas/tests/tslibs/test_api.py

+2
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ def test_namespace():
2525
]
2626

2727
api = [
28+
"BaseOffset",
2829
"NaT",
2930
"NaTType",
3031
"iNaT",
@@ -34,6 +35,7 @@ def test_namespace():
3435
"Period",
3536
"IncompatibleFrequency",
3637
"Resolution",
38+
"Tick",
3739
"Timedelta",
3840
"Timestamp",
3941
"delta_to_nanoseconds",

0 commit comments

Comments
 (0)