Sub topic 3
Recording a check-in
This chapter builds the function that records one check-in. It is small, but the streak, longest streak and completion rate in later chapters all depend on what it stores. If it stores bad data, every later number is wrong.
You should already know Python dictionaries, sets and functions, and the date class from the datetime module. The previous chapter chose a data model: a dictionary that maps each habit name to a set of calendar dates. This chapter writes to that structure.
What a check-in means
A check-in is a statement that a habit was done on a particular calendar day. It has three properties:
- It is yes or no. There is no count and no time of day.
- It belongs to one habit and one date.
- Recording it twice means the same as recording it once.
The third property is the one that shapes the code. People tap a button twice, run a script again after a crash, or backfill a day they already logged. A check-in operation that is safe to repeat is called idempotent. You get that for free if you store dates in a set.
The basic function
Here is the smallest version:
from datetime import date
log = {} # habit name -> set of dates on which it was done
def check_in(habit, day=None):
day = day or date.today()
log.setdefault(habit, set()).add(day)
check_in("read")
check_in("read") # a duplicate check-in on the same day changes nothing
print(len(log["read"])) # 1Each line does a specific job:
day = day or date.today()uses today when the caller passes no date. Adateobject is always truthy, sooris safe here. This would be a bug ifdaycould be0or an empty string, which is one reason to prefer an explicitis Nonetest later.log.setdefault(habit, set())returns the existing set for the habit. If the habit is new, it first inserts an empty set and returns that..add(day)inserts the date. If the date is already in the set, nothing happens and no error is raised.
The diagram shows the path a call takes.
Why a set and not a list
A list of dates would work, but you would have to guard against duplicates yourself:
def check_in_list(habit, day):
days = log_list.setdefault(habit, [])
if day not in days: # linear scan on every call
days.append(day)The set version has three advantages:
- No duplicates by construction. You cannot forget the guard, and no later code needs to deduplicate.
- Fast membership tests.
day in daystakes roughly constant time. The streak function from the next chapter asks that question once per day it walks back, so this matters. - No false ordering. A set makes no promise about order, so no code can depend on insertion order by accident. When order matters, as in the longest-streak calculation, you call
sorted()explicitly.
The cost is that sets are not JSON serializable. You will convert them to sorted lists when saving, in the persistence chapter.
Making the function report what happened
The basic function is silent. A caller cannot tell whether the check-in was new or a repeat. That is useful for a command-line interface that should say "Already logged today" instead of pretending something changed. Return a boolean:
from datetime import date
log = {}
def check_in(habit, day=None):
"""Record that `habit` was done on `day`. Return True if this was new."""
day = date.today() if day is None else day
days = log.setdefault(habit, set())
if day in days:
return False
days.add(day)
return True
print(check_in("read", date(2026, 11, 25))) # True
print(check_in("read", date(2026, 11, 25))) # False
print(sorted(log["read"])) # [datetime.date(2026, 11, 25)]The function is still idempotent: the second call leaves the data unchanged. The only difference is that it now tells the caller so. Returning information instead of printing it keeps the function reusable, because the CLI decides what to say.
Validating the inputs
The function sits at the boundary where outside values enter your data. Three kinds of bad input are common, and each one causes a hard-to-trace bug later.
Datetimes that look like dates
datetime.now() returns a datetime, which is a subclass of date. It is easy to pass one by mistake, and it will be accepted:
from datetime import date, datetime
d1 = date(2026, 11, 27)
d2 = datetime(2026, 11, 27, 8, 52)
print(d1 == d2) # False: a date never equals a datetime
print({d1, d2}) # two separate elementsThe set now holds two entries for one calendar day. A streak walk that subtracts one day at a time would look for date(2026, 11, 26) and never find the datetime entry. Convert at the boundary:
if isinstance(day, datetime):
day = day.date()The isinstance check must come from datetime, not date, because every datetime is also a date.
Dates in the future
A check-in for tomorrow claims something that has not happened. It would also inflate the streak if tomorrow's date were logged early. Reject it:
if day > date.today():
raise ValueError(f"cannot check in on a future date: {day}")Habit names that differ only by form
"Read", "read" and "read " are three different dictionary keys. A user who types them at different times would end up with three habits. Normalize the name before using it as a key:
habit = habit.strip().lower()
if not habit:
raise ValueError("habit name must not be empty")Lowercasing is a choice. It fits a tracker with short names typed by one person. If you want to display names exactly as typed, store a separate display name.
The validated version
Putting these together:
from datetime import date, datetime
log = {} # habit name -> set of dates on which it was done
def check_in(habit, day=None):
"""Record that `habit` was done on `day` (default: today).
Returns True if the check-in was new, False if it was already logged.
Raises ValueError for an empty name or a future date.
"""
habit = habit.strip().lower()
if not habit:
raise ValueError("habit name must not be empty")
today = date.today()
if day is None:
day = today
elif isinstance(day, datetime):
day = day.date()
if day > today:
raise ValueError(f"cannot check in on a future date: {day}")
days = log.setdefault(habit, set())
if day in days:
return False
days.add(day)
return True
print(check_in(" Read ", date(2026, 11, 25))) # True
print(check_in("read", datetime(2026, 11, 25, 21, 30))) # False, same day
print(sorted(log)) # ['read']The second call shows the benefit. A datetime at 21:30 on the same day is converted to a date, recognized as a duplicate, and ignored.
Backfilling past days
The day parameter lets you record a day you forgot. This is useful, and it is also the easiest way to damage a streak history, so decide on a policy:
- Allow any past date. This is simple and forgiving. It also means a user can fill every gap and make the streak meaningless.
- Allow a short window, for example yesterday only. This covers the common case of logging in the morning for the night before.
- Allow no backfill. The data is strictly honest, but a forgotten tap becomes a permanent gap.
This tracker allows any past date, because it is a personal tool and the only person cheated is the user. If you share the data or attach rewards to streaks, add a window check next to the future-date check. A limit of one day looks like this:
from datetime import timedelta
if day < today - timedelta(days=1):
raise ValueError("can only backfill yesterday")Undoing a check-in
Mistakes happen, so you need a way to remove a check-in. Use discard rather than remove:
def uncheck(habit, day=None):
"""Remove a check-in. Return True if one was removed."""
habit = habit.strip().lower()
day = date.today() if day is None else day
days = log.get(habit, set())
if day not in days:
return False
days.remove(day)
return TrueNotice that this uses log.get(habit, set()) and not setdefault. Reading a habit that does not exist should not create it. If you used setdefault here, a mistyped name passed to uncheck would leave an empty habit in your data.
The same reasoning explains why check_in does use setdefault: a write to a new habit is meant to create it.
Alternative: defaultdict
You may see this version in other code:
from collections import defaultdict
from datetime import date
log = defaultdict(set)
def check_in(habit, day=None):
log[habit].add(day or date.today())It is shorter, and it behaves the same for writes. The trade-off is on reads. With a defaultdict, any lookup of a missing key creates it:
print(len(log["typo"])) # 0
print(list(log)) # ['typo'] -- a phantom habit now existsWhen the data is later saved, the phantom habit goes into the file. Plain dict with setdefault on writes and get on reads avoids this. For a tracker whose names come from user input, that is the safer default.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Streak is 0 although you logged today | A `datetime` was stored instead of a `date` | Convert with `.date()` at the boundary |
| Same habit appears twice with different spelling | Names were not normalized | `strip().lower()` before using the key |
| `KeyError` when showing a new habit | Reading with `log[habit]` before any check-in | Use `log.get(habit, set())` |
| Empty habit appears after a typo | `setdefault` or `defaultdict` used on a read | Use `get` for reads |
| Check-in lands on the wrong day late at night | `date.today()` uses the computer's local time zone | See the edge cases chapter |
| All habits share one set | A shared default such as `def f(days=set())` | Create the set inside the function |
The last row is a classic. A default argument is evaluated once when the function is defined, so a set() default would be shared by every call. The code in this chapter avoids it by using None as the default and building the set inside the function.
Testing the function
Because check_in takes the date as a parameter, you can test it without waiting for real days to pass. That is the main reason for the day argument. A few plain assertions cover the behavior:
from datetime import date, datetime, timedelta
log.clear()
today = date.today()
assert check_in("read", today) is True
assert check_in("read", today) is False # duplicate
assert check_in("READ", today) is False # same habit, different spelling
assert check_in("read", datetime.now()) is False # datetime is converted
try:
check_in("read", today + timedelta(days=1))
except ValueError:
pass
else:
raise AssertionError("future date was accepted")
assert len(log["read"]) == 1
print("all checks passed")Run this after the validated definition and it prints all checks passed. Keep these assertions. When you add persistence and the CLI, they tell you quickly whether you broke the recording behavior.
Summary of design decisions
- One set of dates per habit, so repeats cannot create duplicates.
- Dates, not datetimes, because the unit of tracking is the calendar day.
- Validate at the entry point, so every other function can trust the data.
- Return a boolean so callers can report what happened.
- Reads use
get, writes usesetdefault, so typos do not create habits.
Exercise
A user calls check_in("run", datetime.now()) without the conversion step in your function, and the log already holds date.today() for "run". What does len(log["run"]) return, and why does it break the streak calculation?
Show answer
It returns 2. A datetime never equals a date, even for the same calendar day, so the set stores both as separate elements. The streak function walks back with date objects, so it finds the plain date but treats the datetime as an unrelated entry. The log then counts one day twice, and any count based on len(days) overstates the days done. Converting with day.date() at the boundary prevents this.
Exercise
Write uncheckrange-free code: modify checkin so that it only accepts days from the last 7 days (today included), and raises ValueError otherwise. Which line of the validated function changes?
Show answer
Replace the future-date test with a window test. After computing today and converting day, use: if not (today - timedelta(days=6) <= day <= today): raise ValueError("day must be within the last 7 days"). This rejects both future dates and dates older than six days before today, so the window covers seven days including today. It needs from datetime import timedelta at the top.