donnemartin/interactive-coding-challenges · error · TypeError
Argument cannot be None
Error message
Argument cannot be None
What it means
Bits.insert_m_into_n raises TypeError('Argument cannot be None') when any of m, n, i, j is None. The routine builds masks and shifts m into a cleared window of n, so all four values must be present integers.
Source
Thrown at bit_manipulation/insert_m_into_n/insert_m_into_n_solution.ipynb:118
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Code"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"class Bits(object):\n",
"\n",
" def insert_m_into_n(self, m, n, i, j):\n",
" if None in (m, n, i, j):\n",
" raise TypeError('Argument cannot be None')\n",
" if i < 0 or j < 0:\n",
" raise ValueError('Index cannot be negative')\n",
" left_mask = -1 << (j + 1)\n",
" right_mask = (1 << i) - 1\n",
" n_mask = left_mask | right_mask\n",
" # Clear bits from j to i, inclusive\n",
" n_cleared = n & n_mask\n",
" # Shift m into place before inserting it into n\n",
" m_mask = m << i\n",
" return n_cleared | m_mask"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Unit Test"
]View on GitHub (pinned to 358f2cc604)
Solutions
- Supply all four values explicitly, e.g. insert_m_into_n(0b10, 0b1000, 2, 4)
- Validate the payload/spec object for missing fields before calling
- Use dict.get with required-check or raise your own clearer error upstream
Example fix
# before
bits.insert_m_into_n(spec.get('m'), spec.get('n'), spec.get('i'), spec.get('j'))
# after
try:
m, n, i, j = spec['m'], spec['n'], spec['i'], spec['j']
except KeyError as e:
raise ValueError(f'missing field {e}')
bits.insert_m_into_n(m, n, i, j) Defensive patterns
Strategy: type-guard
Validate before calling
if None in (m, n, i, j):
raise ValueError('m, n, i, j are all required')
bits.insert_m_into_n(m, n, i, j) Type guard
def all_present(*vals) -> bool:
return all(v is not None for v in vals) Try / catch
try:
result = bits.insert_m_into_n(m, n, i, j)
except TypeError as e:
if 'cannot be None' in str(e):
raise ValueError('incomplete insert spec') from e
raise Prevention
- Validate spec dicts for required keys before unpacking
- Avoid *args splats from possibly-short sequences
- Add required-field checks where you parse bit-window specs
When it happens
Trigger: insert_m_into_n(None, 15, 2, 4), or calling with values unpacked from a tuple/dict that had fewer entries; optional parameters left as None.
Common situations: Parsing 'insert m into n between bits i and j' specs from config where a field is missing; parameter defaults introduced by refactoring.
Related errors
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/727c9dd885d8a2ac.
Report an issue: GitHub.