I\'ve got an Nonetype
value x
, it\'s generally a number, but could be None
. I want to divide it by a number, but Python raises:
That TypeError
only appears when you try to pass int()
None
(which is the only NoneType
value, as far as I know). I would say that your real goal should not be to convert NoneType
to int
or str
, but to figure out where/why you're getting None
instead of a number as expected, and either fix it or handle the None
properly.
I've successfully used int(x or 0) for this type of error, so long as None should equate to 0 in the logic. Note that this will also resolve to 0 in other cases where testing x returns False. e.g. empty list, set, dictionary or zero length string. Sorry, Kindall already gave this answer.
You should check to make sure the value is not None before trying to perform any calculations on it:
my_value = None
if my_value is not None:
print int(my_value) / 2
Note: my_value
was intentionally set to None to prove the code works and that the check is being performed.
int(value or 0)
This will use 0 in the case when you provide any value that Python considers False
, such as None, 0, [], "", etc. Since 0 is False
, you should only use 0 as the alternative value (otherwise you will find your 0s turning into that value).
int(0 if value is None else value)
This replaces only None
with 0. Since we are testing for None
specifically, you can use some other value as the replacement.