How to convert Nonetype to int or string?

前端 未结 10 1992
情歌与酒
情歌与酒 2020-11-29 17:23

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:

<
10条回答
  •  旧时难觅i
    2020-11-29 18:13

    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...

    if x == THING_THAT_RESULTS_IN_NONE:
        result = DEFAULT_VALUE
    else:
        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.

提交回复
热议问题