Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ Each row is a kind of hidden complexity, a pitfall that demonstrates the mechani
| 3 | [Generators delay errors](#3-generators-delay-their-errors) | Exception far from the bug | Validate in a normal function |
| 60 | [`all([])` is `True`](#60-all-is-true-vacuous-truth) | Empty list passes every check | Check non-empty + materialize |
| 61 | [`itertools.groupby` splits unsorted runs](#61-itertoolsgroupby-only-groups-consecutive-runs-and-shares-its-iterator) | Duplicate keys, empty groups | Sort first + materialize groups |
| 74 | [`defaultdict` creates keys on read](#74-defaultdict-creates-keys-on-read) | Typos become plausible zero values | Use `.get()` / validate keys |
| | **Mutability & aliasing** | | |
| 4 | [Mutable default arguments](#4-mutable-default-arguments) | Data bleeds across calls | `None` sentinel |
| 5 | [List multiplication aliasing](#5-list-multiplication-aliasing) | Edit one row, all rows change | List comprehension |
Expand Down Expand Up @@ -211,6 +212,32 @@ print(list(saved[0][1])) # Output: [] (drained when groupby moved to 'bob')

---

### 74. `defaultdict` Creates Keys on Read

`defaultdict` is excellent for deliberate aggregation: `defaultdict(int)` lets a counter start at zero and `defaultdict(list)` lets a group start as an empty list. But accessing a missing key calls its factory and inserts that key. A misspelt service name can therefore look like a healthy service with zero errors instead of raising `KeyError`.

```python
from collections import defaultdict

errors = defaultdict(int, api=12)

service = "apii" # typo
if errors[service] == 0:
print("No errors — service is healthy")

print(dict(errors))
# No errors — service is healthy
# {'api': 12, 'apii': 0} (the typo was inserted)
```

**Why:** `defaultdict.__getitem__` handles a missing key by calling `default_factory()`, storing the result, and returning it. This is helpful during known aggregation, but changes a read into a write.

**The fix:** Use a normal `dict` when absence is an error. If you are using a `defaultdict` but only want to inspect a possible key, use `.get(key, default)` or `if key in mapping:`; neither inserts the key. Validate an externally supplied service name against your registered services before treating its count as meaningful.

[Example](examples/74_defaultdict_missing_key.py)

---

## Mutability & aliasing

### 4. Mutable Default Arguments
Expand Down
28 changes: 28 additions & 0 deletions examples/74_defaultdict_missing_key.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
""""defaultdict turns a missing-key read into an insertion, which can hide typos."""

from collections import defaultdict

# Intended aggregation: this is exactly what defaultdict(int) is good for.
events = [("api", "timeout"), ("orders", "bad_response"), ("api", "connection_reset")]
error_counts = defaultdict(int)
for service, _error in events:
error_counts[service] += 1
assert dict(error_counts) == {"api": 2, "orders": 1}

# Trap: a read of an unknown key creates it with the factory's default.
known_counts = defaultdict(int, api=12)
service = "apii" # A typo; no such registered service exists.
assert known_counts[service] == 0
print(dict(known_counts)) # {'api': 12, 'apii': 0}
assert dict(known_counts) == {"api": 12, "apii": 0}

# The safe inspection path: .get() does not mutate the mapping.
checked_counts = defaultdict(int, api=12)
assert checked_counts.get(service, 0) == 0
assert dict(checked_counts) == {"api": 12}

# When absence is a bug, validate explicitly (or use a plain dict).
if service not in checked_counts:
print(f"Unknown service: {service}")
else:
print(checked_counts[service])
Loading