donnemartin/interactive-coding-challenges · error · TypeError

word cannot be None

Error message

word cannot be None

What it means

Trie.find raises TypeError('word cannot be None') because iterating over None with 'for char in word' would fail; the guard clause rejects None input explicitly. find returns the terminal node if the word exists (and terminates) or None otherwise, but only for string inputs.

Source

Thrown at graphs_trees/trie/trie_solution.ipynb:199

    "\n",
    "\n",
    "class Node(object):\n",
    "\n",
    "    def __init__(self, key, parent=None, terminates=False):\n",
    "        self.key = key\n",
    "        self.terminates = False\n",
    "        self.parent = parent\n",
    "        self.children = {}\n",
    "\n",
    "\n",
    "class Trie(object):\n",
    "\n",
    "    def __init__(self):\n",
    "        self.root = Node('')\n",
    "\n",
    "    def find(self, word):\n",
    "        if word is None:\n",
    "            raise TypeError('word cannot be None')\n",
    "        node = self.root\n",
    "        for char in word:\n",
    "            if char in node.children:\n",
    "                node = node.children[char]\n",
    "            else:\n",
    "                return None\n",
    "        return node if node.terminates else None\n",
    "\n",
    "    def insert(self, word):\n",
    "        if word is None:\n",
    "            raise TypeError('word cannot be None')\n",
    "        node = self.root\n",
    "        parent = None\n",
    "        for char in word:\n",
    "            if char in node.children:\n",
    "                node = node.children[char]\n",
    "            else:\n",
    "                node.children[char] = Node(char, parent=node)\n",

View on GitHub (pinned to 358f2cc604)

Solutions

  1. Check the word is a non-None string before calling find: if word: node = trie.find(word)
  2. Validate at the boundary where the string enters your program
  3. Catch TypeError when None is an expected test input

Example fix

// before
node = trie.find(word)  # TypeError if word is None
// after
if word is not None:
    node = trie.find(word)
else:
    node = None
Defensive patterns

Strategy: validation

Validate before calling

if not isinstance(word, str):
    return None
node = trie.find(word)

Type guard

def is_word(word) -> bool:
    return isinstance(word, str)

Try / catch

try:
    node = trie.find(word)
except TypeError:
    node = None

Prevention

When it happens

Trigger: Calling trie.find(None), or passing a variable that is None because a lookup, parse, or user input produced no value.

Common situations: Processing user input or file tokens where a line/field is missing and becomes None; reusing a variable across find/insert/remove without checking it was set.

Related errors


AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28). Data as JSON: /api/errors/7a89c8ec4f5f5e80. Report an issue: GitHub.