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?
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 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).
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
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
You've got the ternary syntax x if x else '' - is that what you're after?