Is there shorthand for returning a default value if None in Python?

Question:

In C#, I can say x ?? "", which will give me x if x is not null, and the empty string if x is null. I’ve found it useful for working with databases.

Is there a way to return a default value if Python finds None in a variable?

Asked By: nfw

||

Answers:

You can use a conditional expression:

x if x is not None else some_value

Example:

In [22]: x = None

In [23]: print x if x is not None else "foo"
foo

In [24]: x = "bar"

In [25]: print x if x is not None else "foo"
bar
Answered By: Ashwini Chaudhary

You’ve got the ternary syntax x if x else '' – is that what you’re after?

Answered By: Jon Clements

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

Answered By: starhusker
return "default" if x is None else x

try the above.

Answered By: brent.payne
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.