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

Python

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

return "default" if x is None else x

try the above.

Solution 3 - Python

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

Solution 4 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnfwView Question on Stackoverflow
Solution 1 - PythonstarhuskerView Answer on Stackoverflow
Solution 2 - Pythonbrent.payneView Answer on Stackoverflow
Solution 3 - PythonAshwini ChaudharyView Answer on Stackoverflow
Solution 4 - PythonJon ClementsView Answer on Stackoverflow