Is there shorthand for returning a default value if None in Python? [duplicate]
You could use the or
operator:
return x or "default"
Note that this also returns "default"
if x
is any falsy value, including an empty list, 0, empty string, or even datetime.time(0)
(midnight).
You can use a conditional expression:
x if x is not None else some_value
Example:
In [22]: x = NoneIn [23]: print x if x is not None else "foo"fooIn [24]: x = "bar"In [25]: print x if x is not None else "foo"bar