donnemartin/interactive-coding-challenges · error · TypeError
key cannot be None
Error message
key cannot be None
What it means
Raised by Graph.add_node when key is None. Node keys index the graph's nodes dict and drive all lookups (BFS, DFS, shortest path), so None keys are rejected outright. This is a defensive TypeError against malformed graph definitions.
Source
Thrown at graphs_trees/graph/graph.py:50
def remove_neighbor(self, neighbor):
if neighbor is None:
raise TypeError('neighbor cannot be None')
if neighbor.key not in self.adj_nodes:
raise KeyError('neighbor not found')
neighbor.incoming_edges -= 1
del self.adj_weights[neighbor.key]
del self.adj_nodes[neighbor.key]
class Graph:
def __init__(self):
self.nodes = {} # Key = key, val = Node
def add_node(self, key):
if key is None:
raise TypeError('key cannot be None')
if key not in self.nodes:
self.nodes[key] = Node(key)
return self.nodes[key]
def add_edge(self, source_key, dest_key, weight=0):
if source_key is None or dest_key is None:
raise KeyError('Invalid key')
if source_key not in self.nodes:
self.add_node(source_key)
if dest_key not in self.nodes:
self.add_node(dest_key)
self.nodes[source_key].add_neighbor(self.nodes[dest_key], weight)
def add_undirected_edge(self, src_key, dst_key, weight=0):
if src_key is None or dst_key is None:
raise TypeError('key cannot be None')
self.add_edge(src_key, dst_key, weight)
self.add_edge(dst_key, src_key, weight)View on GitHub (pinned to 358f2cc604)
Solutions
- Validate/skip records with missing keys before graph construction
- Default None keys to a generated unique key (e.g. uuid or counter)
- Assert key is not None in a wrapper around graph building code
Example fix
# before
graph.add_node(record.get('id'))
# after
key = record.get('id')
if key is not None:
graph.add_node(key) Defensive patterns
Strategy: validation
Validate before calling
if key is not None:
graph.add_node(key) Type guard
def valid_key(key) -> bool:
return key is not None Try / catch
try:
graph.add_node(key)
except TypeError:
log.warning('skipping node with missing key: %r', key) Prevention
- Validate record IDs before building graphs
- Generate unique keys for records with missing identifiers
When it happens
Trigger: Calling graph.add_node(None); passing a None key derived from data into add_node, add_edge, or add_undirected_edge.
Common situations: Building graphs from records with missing ID fields; a key computed as data.get('id') returning None; refactor changing key type to Optional.
Related errors
- neighbor or weight cannot be None
- neighbor cannot be None
- key cannot be None
- data cannot be None
- key cannot be None
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/657b486cc409580d.
Report an issue: GitHub.