Proper exception to raise if None encountered as argument
There is no "invalid argument" or "null pointer" built-in exception in Python. Instead, most functions raise TypeError
(invalid type such as NoneType
) or ValueError
(correct type, but the value is outside of the accepted domain).
If your function requires an object of a particular class and gets None
instead, it should probably raise TypeError
as you pointed out. In this case, you should check for None
explicitly, though, since an object of correct type may evaluate to boolean False
if it implements __nonzero__
/__bool__
:
if MyArg2 is None:
raise TypeError
Python docs:
TypeError
python2 / python3ValueError
python2 / python3
As others have noted, TypeError
or ValueError
would be natural. If it doesn't seem specific enough, you could subclass whichever of the two exceptions is a better fit. This allows consistent handling of invalid arguments for a broad class of functions while also giving you more detail for the particular function.