python – How to convert Nonetype to int or string?

python – How to convert Nonetype to int or string?

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.

In one of the comments, you say:

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

If its your code, figure out how youre getting None when you expect a number and stop that from happening.

If its someone elses 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 wont return None, because weve restricted the domain.

Theres 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 codes purpose.

python – How to convert Nonetype to int or string?

A common Pythonic way to handle this kind of situation is known as EAFP for Its easier to ask forgiveness than permission. Which usually means writing code that assumes everything is fine, but then wrapping it with a try...except block to handle things—just in case—its not.

Heres that coding style applied to your problem:

    my_value = int(my_value)
except TypeError:
    my_value = 0  # or whatever you want to do

answer = my_value / divisor

Or perhaps the even simpler and slightly faster:

    answer = int(my_value) / divisor
except TypeError:
    answer = 0

The inverse and more traditional approach is known as LBYL which stands for Look before you leap is what @Soviut and some of the others have suggested. For additional coverage of this topic see my answer and associated comments to the question Determine whether a key is present in a dictionary elsewhere on this site.

One potential problem with EAFP is that it can hide the fact that something is wrong with some other part of your code or third-party module youre using, especially when the exceptions frequently occur (and therefore arent really exceptional cases at all).

Leave a Reply

Your email address will not be published. Required fields are marked *