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?
You could use the
return x or "default"
Note that this also returns
x is any falsy value, including an empty list, 0, empty string, or even
return "default" if x is None else x
try the above.
You can use a conditional expression:
x if x is not None else some_value
In : x = None In : print x if x is not None else "foo" foo In : x = "bar" In : print x if x is not None else "foo" bar
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.
You’ve got the ternary syntax
x if x else '' – is that what you’re after?