Skip to content

Raise ValueError for solar dates outside the supported range - #29

Merged
lidaobing merged 2 commits into
lidaobing:masterfrom
bardrop-oss:fix-from-solar-date-out-of-range
Nov 29, 2026
Merged

lidaobing merged 2 commits into
lidaobing:masterfrom
bardrop-oss:fix-from-solar-date-out-of-range

Conversation

@bardrop

@bardrop bardrop commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

What is wrong

from_solar_date() does not fail for solar dates outside the table. It returns a wrong date.

>>> LunarDate.from_solar_date(2100, 2, 9)   # day after the last supported day
LunarDate(2099, 1, 1, 0)                    # wraps back to the start of 2099
>>> LunarDate.from_solar_date(1900, 1, 1)
LunarDate(1900, 1, -29, 0)                  # negative day
>>> LunarDate(2099, 12, 30) + datetime.timedelta(days=1)
LunarDate(2099, 1, 1, 0)

Expected: a ValueError, like to_solar_date() already raises for years outside [1900, 2100).

The wrapped result is the worst case. It looks like a valid date, so the caller gets a wrong answer with no error.

The fix

_from_offset() now checks the offset against the table range first. If it is before 1900-01-31 or on/after 2100-02-09, it raises:

ValueError: solar date out of range [1900-01-31, 2100-02-09)

Dates inside the range are not changed.

The test

New doctests in from_solar_date: the last valid day (2100-02-08), one day before the first day, one day after the last day, and + timedelta past the end.

  • Before the fix: python lunardate.py -> 3 failures.
  • After the fix: python lunardate.py -v -> 80 passed.
  • mypy lunardate.py -> no issues. flake8 (CI selection) -> 0.

from_solar_date() returned bad dates instead of failing when the solar
date was before 1900-01-31 or on/after 2100-02-09. For example
from_solar_date(2100, 2, 9) gave LunarDate(2099, 1, 1, 0), and
from_solar_date(1900, 1, 1) gave LunarDate(1900, 1, -29, 0). Adding a
timedelta past the last day had the same problem.
Comment thread lunardate.py Outdated

offset = int(offset)

if offset < 0 or offset >= sum(YEAR_DAYS):

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about cache sum(YEAR_DAYS) & end_date

@bardrop

bardrop commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

Good idea, done in c644b6d: TOTAL_DAYS and END_DATE are computed once at module load, next to YEAR_DAYS. Doctests pass.

@lidaobing
lidaobing merged commit 31cb8cf into lidaobing:master Nov 29, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants