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

Posted on

Question :

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

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

||

Answer #1:

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

Answer #2:

return "default" if x is None else x

try the above.

Answered By: brent.payne

Answer #3:

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

Answer #4:

x or "default"

works best — i can even use a function call inline, without executing it twice or using extra variable:

self.lineEdit_path.setText( self.getDir(basepath) or basepath )

I use it when opening Qt’s dialog.getExistingDirectory() and canceling, which returns empty string.

Answered By: zoigo

Answer #5:

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

Answered By: Jon Clements

Leave a Reply

Your email address will not be published. Required fields are marked *