Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Functions & functional toolsMiddleCommonTroubleshooting

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

Compute dynamic defaults at call time
Python
editable · browser sandbox
Result
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.

#functions#gotchas

Sources

The Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semanticsThe Python TutorialPython Software Foundation · Baseline syntax, control flow, functions and module basics