donnemartin/interactive-coding-challenges · error · TypeError

num_pairs cannot be None

Error message

num_pairs cannot be None

What it means

Raised by Parentheses.find_pair when num_pairs is None. It is the first of three guards (None, negative, zero), because the recursive generator assumes an integer count; None is rejected with a TypeError before the num_pairs < 0 comparison would fail with a TypeError anyway.

Source

Thrown at recursion_dynamic/n_pairs_parentheses/n_pairs_parentheses_solution.ipynb:108

  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Parentheses(object):\n",
    "\n",
    "    def find_pair(self, num_pairs):\n",
    "        if num_pairs is None:\n",
    "            raise TypeError('num_pairs cannot be None')\n",
    "        if num_pairs < 0:\n",
    "            raise ValueError('num_pairs cannot be < 0')\n",
    "        if not num_pairs:\n",
    "            return []\n",
    "        results = []\n",
    "        curr_results = []\n",
    "        self._find_pair(num_pairs, num_pairs, curr_results, results)\n",
    "        return results\n",
    "\n",
    "    def _find_pair(self, nleft, nright, curr_results, results):\n",
    "        if nleft == 0 and nright == 0:\n",
    "            results.append(''.join(curr_results))\n",
    "        else:\n",
    "            if nleft >= 0:\n",
    "                self._find_pair(nleft-1, nright, curr_results+['('], results)\n",
    "            if nright > nleft:\n",
    "                self._find_pair(nleft, nright-1, curr_results+[')'], results)"
   ]

View on GitHub (pinned to 358f2cc604)

Solutions

  1. Pass an explicit integer, e.g. find_pair(3)
  2. Convert and default: num_pairs = int(num_pairs or 0)
  3. Validate request params before calling

Example fix

// before
pairs = p.find_pair(request.args.get('n'))
// after
pairs = p.find_pair(int(request.args.get('n', 0)))
Defensive patterns

Strategy: validation

Validate before calling

num_pairs = int(num_pairs) if num_pairs is not None else 0
p.find_pair(num_pairs)

Type guard

def is_nonneg_int(x):
    return isinstance(x, int) and x >= 0

Try / catch

try:
    p.find_pair(n)
except TypeError:
    n = 0
    p.find_pair(n)

Prevention

When it happens

Trigger: Calling find_pair(None). num_pairs = 0 returns [] and a negative value raises ValueError instead — the TypeError is specific to None.

Common situations: num_pairs coming from an unset request parameter or CLI option defaulting to None; a parsed value that failed int() conversion; optional argument never supplied.

Related errors


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