Search code examples
python

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


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?


Solution

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


    Python 3.8+ update: bool(datetime.time(0)) now resolves to True. This was resolved with issue13936. Other "empty" values are still considered "falsy" as expected.