user469652 user469652 - 8 months ago 1092
Python Question

python how to convert Nonetype to int or string

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 says

TypeError: int() argument must be a string or a number, not 'NoneType'

How could I solve that


In one of the comments, you say:

Somehow I got an Nonetype value, it supposed to be an int, but it's now a Nonetype object

If it's your code, figure out how you're getting None when you expect a number and stop that from happening.

If it's someone else's code, find out the conditions under which it gives None and determine a sensible value to use for that, with the usual conditional code:

result = could_return_none(x)

if result is None:
    result = DEFAULT_VALUE

...or even...

    result = DEFAULT_VALUE
    result = could_return_none(x) # But it won't return None, because we've restricted the domain.

There's no reason to automatically use 0 here — solutions that depend on the "false"-ness of None assume you will want this. The DEFAULT_VALUE (if it even exists) completely depends on your code's purpose.