donnemartin/interactive-coding-challenges · error · TypeError
number cannot be None
Error message
number cannot be None
What it means
The Bit class constructor raises TypeError('number cannot be None') when instantiated without a valid integer. This is defensive input validation ensuring self.number always holds an integer before bit operations run.
Source
Thrown at bit_manipulation/bit/bit_solution.ipynb:204
" def validate_index_wrapper(self, *args, **kwargs):\n",
" for arg in args:\n",
" if arg < 0:\n",
" raise IndexError('Invalid index')\n",
" return func(self, *args, **kwargs)\n",
" return validate_index_wrapper"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"class Bit(object):\n",
"\n",
" def __init__(self, number):\n",
" if number is None:\n",
" raise TypeError('number cannot be None')\n",
" self.number = number\n",
"\n",
" @validate_index\n",
" def get_bit(self, index):\n",
" mask = 1 << index\n",
" return self.number & mask != 0\n",
"\n",
" @validate_index\n",
" def set_bit(self, index):\n",
" mask = 1 << index\n",
" self.number |= mask\n",
" return self.number\n",
"\n",
" @validate_index\n",
" def clear_bit(self, index):\n",
" mask = ~(1 << index)\n",
" self.number &= mask\n",
" return self.number\n",View on GitHub (pinned to 358f2cc604)
Solutions
- Pass an actual int, e.g. Bit(12)
- Default the value: Bit(number or 0)
- Validate upstream data source so number is never None
Example fix
# before
b = Bit(data.get('flags'))
# after
flags = data.get('flags')
if flags is None:
raise ValueError("missing 'flags' in data")
b = Bit(flags) Defensive patterns
Strategy: type-guard
Validate before calling
if number is None:
raise ValueError('number is required')
bit = Bit(number) Type guard
def is_int(v) -> bool:
return isinstance(v, int) and not isinstance(v, bool) Try / catch
try:
bit = Bit(number)
except TypeError as e:
if 'cannot be None' in str(e):
number = 0
bit = Bit(number)
else:
raise Prevention
- Avoid dict.get() without default for required constructor values
- Initialize numeric variables to 0, not None
- Type-check inputs at API boundaries
When it happens
Trigger: Bit(None), Bit(number) where number came from an uninitialized variable or a dict.get() that returned None, or forgetting the constructor argument entirely (which raises TypeError for the missing param instead).
Common situations: Loading values from JSON/config where a key is missing (dict.get returns None), passing an optional parameter straight through, or refactoring that changed the constructor signature.
Related errors
- a or b cannot be None
- Invalid argument: None
- num cannot be None
- num cannot be None
- Argument cannot be None
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/667e48e2b0d968aa.
Report an issue: GitHub.