donnemartin/interactive-coding-challenges · error · TypeError

word cannot be None

Error message

word cannot be None

What it means

Raised by Trie.find when word is None. find walks characters of word against child maps, so None would fail at the for-loop; the guard rejects it explicitly. It is also called internally by remove, so a None there surfaces the same error.

Source

Thrown at graphs_trees/trie/trie.py:20


class Node(object):

    def __init__(self, key, parent=None, terminates=False):
        self.key = key
        self.terminates = False
        self.parent = parent
        self.children = {}


class Trie(object):

    def __init__(self):
        self.root = Node('')

    def find(self, word):
        if word is None:
            raise TypeError('word cannot be None')
        node = self.root
        for char in word:
            if char in node.children:
                node = node.children[char]
            else:
                return None
        return node if node.terminates else None

    def insert(self, word):
        if word is None:
            raise TypeError('word cannot be None')
        node = self.root
        parent = None
        for char in word:
            if char in node.children:
                node = node.children[char]
            else:
                node.children[char] = Node(char, parent=node)

View on GitHub (pinned to 358f2cc604)

Solutions

  1. Treat None query as no-match: check for None and return early instead of calling find
  2. Default the query to an empty string when None (find('') returns root behavior, not an error)
  3. Validate user input at the boundary before trie operations

Example fix

# before
node = trie.find(query)  # query may be None

# after
node = trie.find(query) if query is not None else None
Defensive patterns

Strategy: validation

Validate before calling

result = trie.find(word) if word is not None else None

Type guard

def is_searchable(word) -> bool:
    return word is not None and isinstance(word, str)

Try / catch

try:
    node = trie.find(word)
except TypeError:
    node = None  # treat None query as no match

Prevention

When it happens

Trigger: Calling trie.find(None); calling trie.remove(None) (remove delegates to find); passing an unfiltered search term.

Common situations: Search boxes or filters where the query can be unset; optional request parameters flowing into trie lookup without validation.

Related errors


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