donnemartin/interactive-coding-challenges · error · TypeError

val cannot be None

Error message

val cannot be None

What it means

Raised by MathOps.insert in the online_judges variant when val is None (note this variant also has a typo'd attribute mode_ocurrences). The structure maintains running mean/min/max/mode counts that assume numeric input, so None is rejected before any accumulator is touched.

Source

Thrown at online_judges/math_ops/math_ops_solution.ipynb:110

    "\n",
    "\n",
    "class Solution(object):\n",
    "\n",
    "    def __init__(self, upper_limit=100):\n",
    "        self.max = None\n",
    "        self.min = None\n",
    "        # Mean\n",
    "        self.num_items = 0\n",
    "        self.running_sum = 0\n",
    "        self.mean = None\n",
    "        # Mode\n",
    "        self.array = [0] * (upper_limit+1)\n",
    "        self.mode_ocurrences = 0\n",
    "        self.mode = None\n",
    "\n",
    "    def insert(self, val):\n",
    "        if val is None:\n",
    "            raise TypeError('val cannot be None')\n",
    "        if self.max is None or val > self.max:\n",
    "            self.max = val\n",
    "        if self.min is None or val < self.min:\n",
    "            self.min = val\n",
    "        # Calculate the mean\n",
    "        self.num_items += 1\n",
    "        self.running_sum += val\n",
    "        self.mean = self.running_sum / self.num_items\n",
    "        # Calculate the mode\n",
    "        self.array[val] += 1\n",
    "        if self.array[val] > self.mode_ocurrences:\n",
    "            self.mode_ocurrences = self.array[val]\n",
    "            self.mode = val"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},

View on GitHub (pinned to 358f2cc604)

Solutions

  1. Filter or replace None values before inserting
  2. Fix parsing to skip missing entries
  3. Guard at the call site: if val is not None: ops.insert(val)

Example fix

# before
for val in stream:
    ops.insert(val)  # stream may yield None

# after
for val in stream:
    if val is not None:
        ops.insert(val)
Defensive patterns

Strategy: validation

Validate before calling

for v in values:
    if v is None: continue
    ops.insert(v)

Type guard

def is_number(v): return isinstance(v, (int, float))

Try / catch

try:
    ops.insert(v)
except TypeError as e:
    logger.warning('skipping invalid value: %s', e)

Prevention

When it happens

Trigger: Calling insert(None) — inserting values from a stream/dataset with missing entries (JSON null, CSV blank, failed parse).

Common situations: Streaming ingest of dirty data; batch tests; wrappers forwarding optional values unchanged.

Related errors


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