Skip to content

Commit 7cc101f

Browse files
committed
Document interval range direction and equal endpoints
1 parent 69888d0 commit 7cc101f

3 files changed

Lines changed: 25 additions & 4 deletions

File tree

‎docs/docs/interval.md‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -152,8 +152,21 @@ You can pass an amount for the passed unit to control the length of the gap:
152152
```
153153

154154
`amount` must be a non-zero integer. A zero amount raises `ValueError`.
155-
A negative amount whose sign does not match the interval direction
156-
yields an empty iterator (the same way Python's `range()` does).
155+
A positive amount follows the interval direction, including backwards for an
156+
inverted interval. A negative amount walks away from the end, so it yields no
157+
values when the endpoints differ. When both endpoints are equal, either sign
158+
yields that endpoint once.
159+
160+
```python
161+
>>> start = pendulum.datetime(2000, 1, 1)
162+
>>> end = pendulum.datetime(2000, 1, 3)
163+
>>> [dt.day for dt in pendulum.interval(end, start).range('days', 1)]
164+
[3, 2, 1]
165+
>>> list(pendulum.interval(end, start).range('days', -1))
166+
[]
167+
>>> [dt.day for dt in pendulum.interval(start, start).range('days', -1)]
168+
[1]
169+
```
157170

158171
You can also directly iterate over the `Interval` instance,
159172
the unit will be `days` in this case:

‎src/pendulum/interval.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -298,8 +298,8 @@ def range(self, unit: str, amount: int = 1) -> Iterator[_T]:
298298
op = operator.ge
299299

300300
# A negative amount walks the opposite direction of the interval.
301-
# Flip the step so the loop either iterates toward the end (matching
302-
# sign) or is empty immediately (wrong sign), instead of hanging.
301+
# Flip the comparison too, so unequal endpoints yield no values
302+
# instead of looping forever. Equal endpoints are yielded once.
303303
if amount < 0:
304304
amount = -amount
305305
method = "subtract" if method == "add" else "add"

‎tests/interval/test_range.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,3 +139,11 @@ def test_range_wrong_sign_amount_is_empty():
139139

140140
inverted = pendulum.interval(dt2, dt1)
141141
assert list(inverted.range("days", -1)) == []
142+
143+
144+
@pytest.mark.parametrize("amount", [-1, 1])
145+
def test_range_equal_endpoints(amount):
146+
endpoint = pendulum.datetime(2000, 1, 1)
147+
assert list(pendulum.interval(endpoint, endpoint).range("days", amount)) == [
148+
endpoint
149+
]

0 commit comments

Comments
 (0)