donnemartin/interactive-coding-challenges · error · TypeError
key cannot be None
Error message
key cannot be None
What it means
Raised by MinHeap.insert when key is None. Heap ordering comparisons (via _bubble_up) would raise TypeError against None anyway; this guard gives a clearer, earlier error. None keys are fundamentally unorderable in a min-heap.
Source
Thrown at graphs_trees/min_heap/min_heap.py:30
return len(self.array)
def extract_min(self):
if not self.array:
return None
if len(self.array) == 1:
return self.array.pop(0)
minimum = self.array[0]
# Move the last element to the root
self.array[0] = self.array.pop(-1)
self._bubble_down(index=0)
return minimum
def peek_min(self):
return self.array[0] if self.array else None
def insert(self, key):
if key is None:
raise TypeError('key cannot be None')
self.array.append(key)
self._bubble_up(index=len(self.array) - 1)
def _bubble_up(self, index):
if index == 0:
return
index_parent = (index - 1) // 2
if self.array[index] < self.array[index_parent]:
# Swap the indices and recurse
self.array[index], self.array[index_parent] = \
self.array[index_parent], self.array[index]
self._bubble_up(index_parent)
def _bubble_down(self, index):
min_child_index = self._find_smaller_child(index)
if min_child_index == -1:
return
if self.array[index] > self.array[min_child_index]:View on GitHub (pinned to 358f2cc604)
Solutions
- Filter None keys before insertion or substitute a large sentinel priority
- Fix the producer so priorities are always set (validate at ingest)
- If None means 'lowest priority', map it explicitly (e.g. float('inf'))
Example fix
# before
heap.insert(item.get('priority'))
# after
priority = item.get('priority')
heap.insert(priority if priority is not None else float('inf')) Defensive patterns
Strategy: validation
Validate before calling
if key is not None:
heap.insert(key) Type guard
def is_heap_key(value) -> bool:
return value is not None and isinstance(value, (int, float)) Try / catch
try:
heap.insert(key)
except TypeError:
heap.insert(float('inf')) # or skip Prevention
- Map missing priorities to an explicit low-priority sentinel
- Validate priorities at ingest time
When it happens
Trigger: Calling heap.insert(None); inserting values from a stream that contains None (e.g. API responses with optional fields).
Common situations: Priority queues fed by data with missing priorities; mixing Optional values into heap items after a refactor.
Related errors
- data cannot be None
- neighbor or weight cannot be None
- neighbor cannot be None
- key cannot be None
- word cannot be None
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/fc9bc1eb7ca5d0b9.
Report an issue: GitHub.