Skip to content

Commit

Permalink
Add distance_to (#7)
Browse files Browse the repository at this point in the history
* Add `distance_to`

* Version bump

* Fix typechecker warning
  • Loading branch information
raymondjavaxx committed Mar 7, 2024
1 parent 87496ae commit 5054126
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 3 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,12 @@

All notable changes to this project will be documented in this file.

## v0.3.0

### Added

- Added `YearMonth.distance_to()` method for calculating the distance between two `YearMonth` instances.

## v0.2.0

### Added
Expand Down
4 changes: 4 additions & 0 deletions mp_yearmonth/yearmonth.py
Expand Up @@ -167,6 +167,10 @@ def applying_delta(self, months: int) -> "YearMonth":
month = ((self.month + months - 1) % 12) + 1
return YearMonth(year, month)

def distance_to(self, other: "YearMonth") -> int:
"""Return the number of months between this and another YearMonth."""
return (other.year - self.year) * 12 + (other.month - self.month)

@classmethod
def range(cls, start: "YearMonth", end: "YearMonth") -> Iterator["YearMonth"]:
"""Return a list of all months between start and end, inclusive."""
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "mp-yearmonth"
version = "0.2.0"
version = "0.3.0"
description = "A year-month datatype for Python."
keywords = ["year", "month", "date", "calendar"]
authors = ["Ramon Torres <ramon@macropoetry.com>"]
Expand Down
18 changes: 16 additions & 2 deletions tests/test_yearmonth.py
Expand Up @@ -21,10 +21,10 @@ def test_init_handles_out_of_range_year():

def test_init_handles_non_int_values():
with pytest.raises(TypeError, match=r"^year must be an integer$"):
YearMonth("2021", 1)
YearMonth("2021", 1) # type: ignore

with pytest.raises(TypeError, match=r"^month must be an integer$"):
YearMonth(2021, "1")
YearMonth(2021, "1") # type: ignore


def test_str():
Expand Down Expand Up @@ -137,6 +137,20 @@ def test_next():
assert YearMonth(2021, 12).next() == YearMonth(2022, 1)


@pytest.mark.parametrize(
("month", "other_month", "expected_distance"),
[
(YearMonth(2021, 1), YearMonth(2021, 1), 0),
(YearMonth(2021, 1), YearMonth(2021, 2), 1),
(YearMonth(2021, 1), YearMonth(2022, 1), 12),
(YearMonth(2021, 1), YearMonth(2020, 12), -1),
(YearMonth(2021, 1), YearMonth(2020, 1), -12),
],
)
def test_distance_to(month: YearMonth, other_month: YearMonth, expected_distance: int):
assert month.distance_to(other_month) == expected_distance


def test_range():
# Ascending
r = YearMonth.range(YearMonth(2021, 1), YearMonth(2021, 3))
Expand Down

0 comments on commit 5054126

Please sign in to comment.