Home > Software design >  Pythonic way to check returned value for None
Pythonic way to check returned value for None

Time:09-22

I'm looking for a pythonic way for the code below.

Function foo() may return an int or "None" and in that case "None" should be replaced by a default value.

I doubt that this can't be simplified and reduced to a one-liner, I just don't know how to do it ^^

def foo() -> int:
   # code


x = foo()
x = 0 if x is None else x

CodePudding user response:

That is plenty Pythonic and concise (2 lines). The only way to reduce it to 1 line is to use the walrus operator:

x = 0 if (x := foo()) is None else x
#         ^ assigns foo() to x and ^ x is reused here
#^but x is ultimately reassigned here

CodePudding user response:

you can use or operator. If the first argument resolves to False, second one is assigned. Example:

x = foo() or default_value

The issue with that is, if foo() will return 0 for example, default value will be assigned

  • Related