When are default argument values evaluated, and what problem does that cause for a default like `datetime.now()`?
Answer
Default argument expressions are evaluated exactly once, at the moment the `def` statement executes and the function object is created, not on every call. This means `def log(message, timestamp=datetime.now())` captures one fixed timestamp — the moment the module was imported — and every call to `log()` that omits `timestamp` reuses that same stale value forever. The fix is to default to `None` and compute the real value inside the function body: `def log(message, timestamp=None): timestamp = timestamp or datetime.now()`.
Strong answer includes
- defaults evaluated once at def time, not per call
- datetime.now() default freezes at import time
- fix: default to None, compute inside the function body
Practical example
Run the code to see the result.
The bad default is evaluated once when def executes. None is a sentinel that lets the safe version evaluate datetime.now() each time the function is called.
Expected result: The first comparison is True because both calls reuse one datetime object; the second comparison is normally False because each call creates a new timestamp.