timecore 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,478 @@
1
+ """Interval: a single contiguous range of temporal values.
2
+
3
+ An :class:`Interval` is a contiguous set of points of one temporal type
4
+ (``Date``, ``LocalDateTime``, ``DateTime`` or ``Instant``). By default
5
+ intervals are half-open, ``[start, end)``: the start point is included
6
+ and the end point is excluded. :meth:`Interval.closed` builds a closed
7
+ interval ``[start, end]`` whose end point is included.
8
+
9
+ Edge semantics (half-open throughout):
10
+
11
+ * ``start == end`` is a valid empty interval for the half-open form;
12
+ ``Interval.closed(start, start)`` is the single point ``{start}`` and
13
+ is not empty. All empty intervals with the same endpoint type are
14
+ equal: they are all the empty set.
15
+ * Adjacent intervals touch but do not overlap: ``[a, b)`` and ``[b, c)``
16
+ share no point, so :meth:`Interval.overlaps` is ``False`` for them,
17
+ while :meth:`Interval.union` still merges them into ``[a, c)``.
18
+ Two closed intervals ``[a, b]`` and ``[b, c]`` *do* overlap (they
19
+ share ``b``).
20
+ * :meth:`Interval.contains` uses the interval's own end inclusivity
21
+ unless ``end_inclusive`` is passed explicitly, in which case the
22
+ override decides whether the end point counts.
23
+ * :meth:`Interval.difference` may produce a piece that excludes its
24
+ start point (for example, subtracting a closed interval from the
25
+ middle of another closed interval leaves ``(d, b]``). Such pieces are
26
+ representable internally; they are never produced by the public
27
+ constructor, whose start point is always included.
28
+ * For ``Date`` endpoints the day grid is discrete: an interval open at
29
+ both ends, ``(a, b)``, is empty when ``b`` is the day after ``a``,
30
+ because no date lies strictly between consecutive dates. Pieces of
31
+ a difference that would be open on the left are normalized to the
32
+ first contained date, e.g. ``(Jan 5, Jan 10]`` becomes
33
+ ``[Jan 6, Jan 10]``.
34
+
35
+ Set algebra (union, intersection, difference) is computed with the
36
+ ``portion`` library internally; no ``portion`` type or exception ever
37
+ reaches the public API.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ from typing import TYPE_CHECKING, Any, TypeAlias, cast
43
+
44
+ import portion # type: ignore[import-untyped] # portion ships no type stubs
45
+
46
+ from ..core import Date, DateTime, Duration, Instant, LocalDateTime, Period
47
+ from ..errors import InvalidIntervalError
48
+
49
+ if TYPE_CHECKING:
50
+ from .interval_set import IntervalSet
51
+
52
+ __all__ = ["Endpoint", "Interval"]
53
+
54
+ #: The temporal types that can be interval endpoints.
55
+ Endpoint: TypeAlias = Date | LocalDateTime | DateTime | Instant
56
+
57
+ _ENDPOINT_TYPES = (Date, LocalDateTime, DateTime, Instant)
58
+
59
+ # portion ships no type stubs, so every value that flows through it is
60
+ # Unknown to pyright under strict checking. Route all portion access
61
+ # through this untyped alias so the Unknowns stay contained here and
62
+ # never leak into annotated signatures or return types.
63
+ _portion: Any = portion
64
+
65
+
66
+ def _validate_endpoints(start: object, end: object) -> type[Endpoint]:
67
+ """Check that ``start``/``end`` are a valid endpoint pair.
68
+
69
+ Returns the shared endpoint type. Raises
70
+ :class:`~timecore.errors.InvalidIntervalError` for a wrong type, a
71
+ mismatched pair, or ``start > end``.
72
+ """
73
+ if not isinstance(start, _ENDPOINT_TYPES) or not isinstance(end, _ENDPOINT_TYPES):
74
+ raise InvalidIntervalError(
75
+ "Interval endpoints must both be Date, LocalDateTime, DateTime, "
76
+ f"or Instant; got {type(start).__name__} and {type(end).__name__}."
77
+ )
78
+ if type(start) is not type(end):
79
+ raise InvalidIntervalError(
80
+ "Interval endpoints must be of the same type; got "
81
+ f"{type(start).__name__} and {type(end).__name__}."
82
+ )
83
+ if start > end:
84
+ raise InvalidIntervalError(
85
+ f"Interval start ({start}) must not be after end ({end})."
86
+ )
87
+ return type(start)
88
+
89
+
90
+ def require_endpoint(value: object, label: str) -> Endpoint:
91
+ """Return ``value`` if it is an endpoint value, else raise TypeError.
92
+
93
+ ``label`` names the operation for the error message, e.g.
94
+ ``"Interval.contains()"``. Takes ``object`` so the runtime check
95
+ is meaningful to pyright even when callers pass typed values.
96
+ """
97
+ if not isinstance(value, _ENDPOINT_TYPES):
98
+ raise TypeError(
99
+ f"{label} expects a Date, LocalDateTime, DateTime, or Instant; "
100
+ f"got {type(value).__name__}."
101
+ )
102
+ return value
103
+
104
+
105
+ def require_interval(value: object, label: str) -> Interval:
106
+ """Return ``value`` if it is an Interval, else raise TypeError.
107
+
108
+ ``label`` names the operation for the error message, e.g.
109
+ ``"Interval.union()"``.
110
+ """
111
+ if not isinstance(value, Interval):
112
+ raise TypeError(f"{label} expects an Interval; got {type(value).__name__}.")
113
+ return value
114
+
115
+
116
+ def _to_portion_atom(
117
+ start: Endpoint,
118
+ end: Endpoint,
119
+ *,
120
+ start_inclusive: bool,
121
+ end_inclusive: bool,
122
+ ) -> Any:
123
+ """Convert interval bounds to a ``portion`` atomic interval."""
124
+ if start_inclusive and end_inclusive:
125
+ return _portion.closed(start, end)
126
+ if start_inclusive:
127
+ return _portion.closedopen(start, end)
128
+ if end_inclusive:
129
+ return _portion.openclosed(start, end)
130
+ return _portion.open(start, end)
131
+
132
+
133
+ def from_portion_atom(atom: Any) -> Interval | None:
134
+ """Convert a ``portion`` atomic interval back to an :class:`Interval`.
135
+
136
+ Internal to the ``timecore.interval`` subpackage; not part of the
137
+ public API. Returns ``None`` for atoms that contain no point (an
138
+ empty atom, or -- for ``Date`` endpoints -- an interval open at
139
+ both ends whose bounds are consecutive dates). ``Date`` atoms open
140
+ on the left are normalized to the first contained date, e.g.
141
+ ``(Jan 5, Jan 10]`` becomes ``[Jan 6, Jan 10]``.
142
+ """
143
+ lower = atom.lower
144
+ upper = atom.upper
145
+ start_inclusive = atom.left == _portion.CLOSED
146
+ end_inclusive = atom.right == _portion.CLOSED
147
+ if isinstance(lower, Date):
148
+ if not start_inclusive:
149
+ # Discrete day grid: the first contained date is the day
150
+ # after the excluded bound.
151
+ lower = lower + Period(days=1)
152
+ start_inclusive = True
153
+ if lower > upper:
154
+ return None
155
+ if lower == upper and not end_inclusive:
156
+ return None
157
+ return Interval(lower, upper, end_inclusive=end_inclusive)
158
+ if start_inclusive:
159
+ return Interval(lower, upper, end_inclusive=end_inclusive)
160
+ # Only difference-produced pieces exclude their start point; the
161
+ # public constructor cannot build them.
162
+ from_bounds = Interval._from_bounds # pyright: ignore[reportPrivateUsage]
163
+ return from_bounds(lower, upper, start_inclusive=False, end_inclusive=end_inclusive)
164
+
165
+
166
+ class Interval:
167
+ """A contiguous range of temporal values.
168
+
169
+ Example:
170
+ >>> Interval(Date(2026, 1, 1), Date(2026, 1, 8))
171
+ Interval(Date(2026, 1, 1), Date(2026, 1, 8))
172
+ >>> Interval.closed(Date(2026, 1, 1), Date(2026, 1, 8))
173
+ Interval.closed(Date(2026, 1, 1), Date(2026, 1, 8))
174
+ """
175
+
176
+ __slots__ = ("_end", "_end_inclusive", "_start", "_start_inclusive")
177
+
178
+ _start: Endpoint
179
+ _end: Endpoint
180
+ _start_inclusive: bool
181
+ _end_inclusive: bool
182
+
183
+ def __init__(
184
+ self, start: Endpoint, end: Endpoint, *, end_inclusive: bool = False
185
+ ) -> None:
186
+ """Create a half-open interval ``[start, end)``.
187
+
188
+ Pass ``end_inclusive=True`` (or use :meth:`closed`) for a
189
+ closed interval ``[start, end]``. The endpoints must be of the
190
+ same type (``Date``, ``LocalDateTime``, ``DateTime`` or
191
+ ``Instant``); ``start > end`` raises
192
+ :class:`~timecore.errors.InvalidIntervalError`. ``start == end``
193
+ is a valid empty interval for the half-open form.
194
+ """
195
+ _validate_endpoints(start, end)
196
+ self._start = start
197
+ self._end = end
198
+ self._start_inclusive = True
199
+ self._end_inclusive = end_inclusive
200
+
201
+ @classmethod
202
+ def closed(cls, start: Endpoint, end: Endpoint) -> Interval:
203
+ """Create a closed interval ``[start, end]`` (end included).
204
+
205
+ ``Interval.closed(a, a)`` is the single point ``{a}`` and is
206
+ not empty.
207
+ """
208
+ return cls._from_bounds(start, end, start_inclusive=True, end_inclusive=True)
209
+
210
+ @classmethod
211
+ def _from_bounds(
212
+ cls,
213
+ start: Endpoint,
214
+ end: Endpoint,
215
+ *,
216
+ start_inclusive: bool,
217
+ end_inclusive: bool,
218
+ ) -> Interval:
219
+ """Internal constructor with explicit bound inclusivity.
220
+
221
+ The public constructor always includes the start point; this
222
+ constructor additionally serves pieces produced by
223
+ :meth:`difference`, which may exclude their start point.
224
+ """
225
+ _validate_endpoints(start, end)
226
+ obj = cls.__new__(cls)
227
+ obj._start = start
228
+ obj._end = end
229
+ obj._start_inclusive = start_inclusive
230
+ obj._end_inclusive = end_inclusive
231
+ return obj
232
+
233
+ @property
234
+ def start(self) -> Endpoint:
235
+ """The start point of the interval (always included, except for
236
+ pieces produced by :meth:`difference`, which may exclude it)."""
237
+ return self._start
238
+
239
+ @property
240
+ def end(self) -> Endpoint:
241
+ """The end point of the interval."""
242
+ return self._end
243
+
244
+ @property
245
+ def is_empty(self) -> bool:
246
+ """Whether the interval contains no point.
247
+
248
+ A half-open interval with ``start == end`` is empty; a closed
249
+ interval with ``start == end`` is a single point and is not
250
+ empty. For ``Date`` endpoints an interval open at both ends is
251
+ also empty when its bounds are consecutive dates.
252
+ """
253
+ start = self._start
254
+ end = self._end
255
+ if start == end:
256
+ return not (self._start_inclusive and self._end_inclusive)
257
+ if (
258
+ isinstance(start, Date)
259
+ and isinstance(end, Date)
260
+ and not self._start_inclusive
261
+ and not self._end_inclusive
262
+ ):
263
+ # Discrete day grid: no date lies strictly between
264
+ # consecutive dates.
265
+ return (end.to_date() - start.to_date()).days < 2
266
+ return False
267
+
268
+ @property
269
+ def duration(self) -> Duration | Period:
270
+ """The span ``end - start`` of the interval.
271
+
272
+ A :class:`~timecore.core.Duration` for ``Instant``,
273
+ ``DateTime`` and ``LocalDateTime`` endpoints (computed with
274
+ that type's arithmetic, so a ``DateTime`` interval spanning a
275
+ DST transition is not assumed to be a whole number of 24-hour
276
+ days); a :class:`~timecore.core.Period` in whole days for
277
+ ``Date`` endpoints. The span does not depend on whether the
278
+ bounds are inclusive: a closed ``[a, b]`` and a half-open
279
+ ``[a, b)`` have the same duration.
280
+ """
281
+ start = self._start
282
+ end = self._end
283
+ if isinstance(start, Date) and isinstance(end, Date):
284
+ # Date.__sub__ also accepts Period/Duration operands, so
285
+ # its static return type is Date | Period; subtracting two
286
+ # Dates always yields a Period.
287
+ return cast(Period, end - start)
288
+ if isinstance(start, LocalDateTime) and isinstance(end, LocalDateTime):
289
+ # Likewise, LocalDateTime.__sub__ is statically
290
+ # LocalDateTime | Duration; subtracting two datetimes
291
+ # always yields a Duration.
292
+ return cast(Duration, end - start)
293
+ if isinstance(start, DateTime) and isinstance(end, DateTime):
294
+ return cast(Duration, end - start)
295
+ if isinstance(start, Instant) and isinstance(end, Instant):
296
+ return end - start
297
+ # Unreachable: the constructor guarantees matching endpoint types.
298
+ raise AssertionError(f"mismatched interval endpoints: {start!r}, {end!r}")
299
+
300
+ def contains(self, point: Endpoint, *, end_inclusive: bool | None = None) -> bool:
301
+ """Whether ``point`` lies in the interval.
302
+
303
+ Uses the interval's own end inclusivity unless
304
+ ``end_inclusive`` is given, in which case the override decides
305
+ whether the end point counts. An empty interval contains
306
+ nothing. ``point`` must be of the interval's endpoint type;
307
+ a different temporal type raises
308
+ :class:`~timecore.errors.InvalidIntervalError`.
309
+ """
310
+ point = require_endpoint(point, "Interval.contains()")
311
+ if type(point) is not type(self._start):
312
+ raise InvalidIntervalError(
313
+ "Interval.contains() point must be of the interval's "
314
+ f"endpoint type ({type(self._start).__name__}); "
315
+ f"got {type(point).__name__}."
316
+ )
317
+ if self.is_empty:
318
+ return False
319
+ if point < self._start or (point == self._start and not self._start_inclusive):
320
+ return False
321
+ effective_end_inclusive = (
322
+ self._end_inclusive if end_inclusive is None else end_inclusive
323
+ )
324
+ if point > self._end:
325
+ return False
326
+ return point < self._end or effective_end_inclusive
327
+
328
+ def overlaps(self, other: Interval) -> bool:
329
+ """Whether this interval and ``other`` share at least one point.
330
+
331
+ Adjacent intervals do not overlap: ``[a, b)`` and ``[b, c)``
332
+ share no point. Two closed intervals sharing an endpoint do
333
+ overlap. Empty intervals never overlap anything.
334
+ """
335
+ other = require_interval(other, "Interval.overlaps()")
336
+ if type(other._start) is not type(self._start):
337
+ raise InvalidIntervalError(
338
+ "Interval.overlaps() requires intervals with the same "
339
+ f"endpoint type; got {type(self._start).__name__} and "
340
+ f"{type(other._start).__name__}."
341
+ )
342
+ if self.is_empty or other.is_empty:
343
+ return False
344
+ # Delegate to intersection(): for Date endpoints an intersection
345
+ # that portion reports as non-empty can still contain no date
346
+ # (e.g. an interval open at both ends between consecutive
347
+ # dates), and intersection() already normalizes that to None.
348
+ return self.intersection(other) is not None
349
+
350
+ def union(self, other: Interval) -> Interval:
351
+ """The smallest interval covering both intervals.
352
+
353
+ Requires the intervals to overlap or be adjacent (touching);
354
+ disjoint intervals raise
355
+ :class:`~timecore.errors.InvalidIntervalError` because their
356
+ union is not a single interval -- use
357
+ :class:`IntervalSet` for that. Empty intervals contribute
358
+ nothing: the union with an empty interval is the other
359
+ interval.
360
+ """
361
+ other = require_interval(other, "Interval.union()")
362
+ if type(other._start) is not type(self._start):
363
+ raise InvalidIntervalError(
364
+ "Interval.union() requires intervals with the same "
365
+ f"endpoint type; got {type(self._start).__name__} and "
366
+ f"{type(other._start).__name__}."
367
+ )
368
+ if self.is_empty:
369
+ return other
370
+ if other.is_empty:
371
+ return self
372
+ merged = self._to_portion() | other._to_portion()
373
+ atoms = list(merged)
374
+ if len(atoms) != 1:
375
+ raise InvalidIntervalError(
376
+ "Interval.union() requires overlapping or adjacent "
377
+ f"intervals; {self!r} and {other!r} are disjoint."
378
+ )
379
+ result = from_portion_atom(atoms[0])
380
+ if result is None: # pragma: no cover - merging non-empty intervals
381
+ raise AssertionError(f"union of non-empty intervals is empty: {merged!r}")
382
+ return result
383
+
384
+ def intersection(self, other: Interval) -> Interval | None:
385
+ """The interval common to both intervals, or ``None``.
386
+
387
+ Returns ``None`` when the intervals share no point -- that
388
+ includes adjacent half-open intervals such as ``[a, b)`` and
389
+ ``[b, c)``.
390
+ """
391
+ other = require_interval(other, "Interval.intersection()")
392
+ if type(other._start) is not type(self._start):
393
+ raise InvalidIntervalError(
394
+ "Interval.intersection() requires intervals with the "
395
+ f"same endpoint type; got {type(self._start).__name__} "
396
+ f"and {type(other._start).__name__}."
397
+ )
398
+ if self.is_empty or other.is_empty:
399
+ return None
400
+ shared = self._to_portion() & other._to_portion()
401
+ if shared.empty:
402
+ return None
403
+ return from_portion_atom(next(iter(shared)))
404
+
405
+ def difference(self, other: Interval) -> IntervalSet:
406
+ """The parts of this interval not covered by ``other``.
407
+
408
+ Always returns an :class:`IntervalSet`: empty when ``other``
409
+ covers this interval entirely, one interval when ``other``
410
+ overlaps one end, and two intervals when ``other`` cuts out
411
+ the middle.
412
+ """
413
+ from .interval_set import IntervalSet
414
+
415
+ other = require_interval(other, "Interval.difference()")
416
+ if type(other._start) is not type(self._start):
417
+ raise InvalidIntervalError(
418
+ "Interval.difference() requires intervals with the same "
419
+ f"endpoint type; got {type(self._start).__name__} and "
420
+ f"{type(other._start).__name__}."
421
+ )
422
+ # _from_portion is private to IntervalSet; this is the
423
+ # subpackage-internal construction path for set results.
424
+ from_portion = IntervalSet._from_portion # pyright: ignore[reportPrivateUsage]
425
+ return from_portion(self._to_portion() - other._to_portion(), type(self._start))
426
+
427
+ def _to_portion(self) -> Any:
428
+ """This interval as a ``portion`` atomic interval."""
429
+ return _to_portion_atom(
430
+ self._start,
431
+ self._end,
432
+ start_inclusive=self._start_inclusive,
433
+ end_inclusive=self._end_inclusive,
434
+ )
435
+
436
+ def __eq__(self, other: object) -> bool:
437
+ if not isinstance(other, Interval):
438
+ return NotImplemented
439
+ if type(other._start) is not type(self._start):
440
+ return False
441
+ # Intervals are sets of points: all empty intervals with the
442
+ # same endpoint type are equal (they are all the empty set).
443
+ if self.is_empty and other.is_empty:
444
+ return True
445
+ return (
446
+ self._start == other._start
447
+ and self._end == other._end
448
+ and self._start_inclusive == other._start_inclusive
449
+ and self._end_inclusive == other._end_inclusive
450
+ )
451
+
452
+ def __hash__(self) -> int:
453
+ if self.is_empty:
454
+ return hash((type(self._start), "empty"))
455
+ return hash(
456
+ (
457
+ type(self._start),
458
+ self._start,
459
+ self._end,
460
+ self._start_inclusive,
461
+ self._end_inclusive,
462
+ )
463
+ )
464
+
465
+ def __repr__(self) -> str:
466
+ if self._start_inclusive and self._end_inclusive:
467
+ return f"Interval.closed({self._start!r}, {self._end!r})"
468
+ if not self._start_inclusive:
469
+ # Only produced by Interval.difference(); there is no public
470
+ # constructor for an interval excluding its start point.
471
+ return (
472
+ "Interval._from_bounds("
473
+ f"{self._start!r}, {self._end!r}, "
474
+ f"start_inclusive=False, end_inclusive={self._end_inclusive!r})"
475
+ )
476
+ if self._end_inclusive:
477
+ return f"Interval({self._start!r}, {self._end!r}, end_inclusive=True)"
478
+ return f"Interval({self._start!r}, {self._end!r})"