Sub topic 9
Edge cases: today, gaps and duplicates
This chapter assumes you have the check_in and current_streak functions from the earlier chapters. You should also be comfortable with date, timedelta and sets. The goal is to find the inputs that make those functions give a wrong or surprising answer, and to pin the correct behavior down with tests.
Three situations to get right
Most streak bugs come from one of three cases:
- Today is not logged yet. The user opens the tracker at 9 a.m. A streak of 12 should not show as 0 just because the day has barely started.
- There is a gap. One missed day ends the streak. Earlier days must not be counted across the gap.
- The same day is logged twice. A second check-in must not change any number.
The decision flow for the current streak looks like this:
Pinning the behavior with tests
Passing today explicitly makes the function deterministic. You don't have to depend on the real clock. This example runs as shown:
from datetime import date, timedelta
def current_streak(days, today=None):
today = today or date.today()
day = today if today in days else today - timedelta(days=1)
streak = 0
while day in days:
streak += 1
day -= timedelta(days=1)
return streak
today = date(2026, 11, 27)
def back(*offsets):
return {today - timedelta(days=n) for n in offsets}
# Today not logged yet: the streak survives and counts from yesterday.
assert current_streak(back(1, 2, 3), today) == 3
# Today logged: it is included.
assert current_streak(back(0, 1, 2, 3), today) == 4
# A gap ends the run. The day before the gap is not counted.
assert current_streak(back(0, 1, 3, 4), today) == 2
# Yesterday and today both missing: the streak is broken.
assert current_streak(back(2, 3, 4), today) == 0
# No data at all.
assert current_streak(set(), today) == 0
print("all streak checks passed")The third assertion shows why a set of dates works well here. The loop stops at the first missing day, so older check-ins are never reached.
Duplicates
Because each habit stores a set of dates, calling check_in twice on one day adds the same date object twice, and the set keeps one copy. len(log["read"]) stays at 1, and the streak and completion rate are unchanged. If you had used a list, every duplicate would inflate the completion rate. longest_streak would also break, because two equal dates are zero days apart and not one.
Common errors
Mixing `datetime` and `date`
A datetime never equals a date, even on the same calendar day. Values like this slip into a log silently and are never matched by the streak loop:
from datetime import date, datetime
stamp = datetime(2026, 11, 27, 9, 3)
print(stamp == date(2026, 11, 27)) # False
print(stamp.date() == date(2026, 11, 27)) # TrueConvert at the boundary with .date(), and store only date objects. Loading from JSON with date.fromisoformat already follows this rule.
Future dates
The streak walk starts at today, so a future date is ignored by current_streak. longest_streak and completion_rate can still be affected by it. A mistyped year can then create a streak that never ends. Reject such input when recording:
from datetime import date
def check_in(log, habit, day=None):
day = day or date.today()
if day > date.today():
raise ValueError("cannot check in for a future date")
log.setdefault(habit, set()).add(day)
log = {}
check_in(log, "read")
check_in(log, "read")
print(len(log["read"])) # 1The clock and the time zone
date.today() uses the computer's local date. If the user travels or the computer's time zone changes, "today" can jump a day. A check-in made at 11:59 p.m. and one made at 12:01 a.m. belong to different days, which is correct. A single-user local tracker rarely needs more than this. Be aware of the limit, though, because a shared server would need an explicit time zone.
Passing an empty set to `longest_streak`
With no days, the loop never runs and the function returns 0. This is correct, so no special case is needed. Test it anyway:
from datetime import timedelta
def longest_streak(days):
best = run = 0
previous = None
for day in sorted(days):
if previous is not None and day - previous == timedelta(days=1):
run += 1
else:
run = 1
best = max(best, run)
previous = day
return best
assert longest_streak(set()) == 0
print("empty log handled")Checklist
- Pass
todayas a parameter so tests do not depend on the real date. - Test the empty log, today missing, a single gap and a duplicate.
- Store only
dateobjects. - Reject future dates when recording.
Exercise
A log contains the dates for today, yesterday and four days ago, and it also contains datetime.now() stored by mistake for the day before yesterday. What does current_streak return, and why?
Show answer
It returns 2. Today and yesterday are consecutive date objects. The day before yesterday is stored as a datetime, which does not equal the date for that day, so the loop sees that day as missing and stops. Converting with .date() before storing would still not give 4, because three days ago is not logged. The correct streak would then be 3.