Skip to content

Commit

Permalink
Add support for membership operators
Browse files Browse the repository at this point in the history
  • Loading branch information
raymondjavaxx committed Dec 6, 2023
1 parent af6f1cc commit b97d12b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
5 changes: 5 additions & 0 deletions mp_yearmonth/yearmonth.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@ def __sub__(self, other) -> "YearMonth":
return self.applying_delta(-other)
return NotImplemented

def __contains__(self, other) -> bool:
if isinstance(other, datetime.date) or isinstance(other, datetime.datetime):
return self.year == other.year and self.month == other.month
return False

# Public interface

@property
Expand Down
18 changes: 18 additions & 0 deletions tests/test_yearmonth.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,24 @@ def test_sub():
assert ym - 2 == YearMonth(2020, 11)


def test_contains_handles_dates():
assert datetime.date(2021, 1, 1) in YearMonth(2021, 1)
assert datetime.date(2021, 1, 31) in YearMonth(2021, 1)
assert datetime.date(2021, 2, 1) not in YearMonth(2021, 1)


def test_contains_handles_datetimes():
assert datetime.datetime(2021, 1, 1, hour=12, minute=30) in YearMonth(2021, 1)
assert datetime.datetime(2021, 1, 31, hour=12, minute=30) in YearMonth(2021, 1)
assert datetime.datetime(2021, 2, 1, hour=12, minute=30) not in YearMonth(2021, 1)


def test_contains_handles_unsupported_types():
assert 1 not in YearMonth(2021, 1)
assert 2021 not in YearMonth(2021, 1)
assert "test" not in YearMonth(2021, 1)


def test_bounds():
ym1 = YearMonth(2021, 1)
assert ym1.bounds() == (datetime.date(2021, 1, 1), datetime.date(2021, 1, 31))
Expand Down

0 comments on commit b97d12b

Please sign in to comment.