ML Foundations

Distinguish a missing dictionary key from None

Use an explicit sentinel when None is a valid dictionary value.

Example results for Distinguish a missing dictionary key from None. absent: not provided
Illustration: Original illustration by Tensor Almanac
Evidence and testing

Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.

A stored None is still a value

A dictionary can contain a key whose value is None. Calling get with no explicit default returns None both for that stored value and for an absent key, so the return value alone does not distinguish those cases. [1]

When absence and explicit None have different meanings, use membership testing or pass a unique sentinel as the default. Compare a sentinel by identity, so ordinary values such as zero are not confused with absence. [1, 2]

References: [1], [2]

Classify three cases

Run python examples/dict_missing_vs_none.py. The example creates one unique sentinel object and passes it to get for each settings dictionary. An absent timeout returns the sentinel, an explicit None returns None, and a stored zero returns zero. [1]

The is comparisons test object identity. The assertions verify each case independently, including zero, which a general truthiness check would treat as false. [2]

Executed with local Python; stdout and checksum are stored in private evidence.

MISSING = object()

records = {"absent": {}, "explicit": {"timeout": None}, "zero": {"timeout": 0}}
for name, settings in records.items():
    value = settings.get("timeout", MISSING)
    if value is MISSING:
        state = "not provided"
    elif value is None:
        state = "explicit None"
    else:
        state = "value " + str(value)
    print(name + ": " + state)

assert records["absent"].get("timeout", MISSING) is MISSING
assert records["explicit"].get("timeout", MISSING) is None
assert records["zero"].get("timeout", MISSING) == 0

Recorded output

absent: not provided
explicit: explicit None
zero: value 0

References: [1], [2]

Keep the sentinel local to the decision

Use the same sentinel object for the lookup and identity check. The example uses a local constant that cannot appear in the fixture as a legitimate stored value. Membership testing is another direct option when a separate lookup is convenient. [1, 2]

This pattern distinguishes states; it does not determine what a missing value or explicit None should mean for an application. Document that policy where the data is consumed.

References: [1], [2]

Sources

  1. Python dictionary get
  2. Python identity comparisons