In C# there's a null-coalescing operator (written as ??) that allows for easy (short) null checking during assignment:
string s = null;
var other = s ?? "some default value";
Is there a python equivalent?
I know that I can do:
s = None
other = s if s else "some default value"
But is there an even shorter way (where I don't need to repeat s)?
Ok, it must be clarified how the
oroperator works. It is a boolean operator, so it works in a boolean context. If the values are not boolean, they are converted to boolean for the purposes of the operator.Note that the
oroperator does not return onlyTrueorFalse. Instead, it returns the first operand if the first operand evaluates to true, and it returns the second operand if the first operand evaluates to false.In this case, the expression
x or yreturnsxif it isTrueor evaluates to true when converted to boolean. Otherwise, it returnsy. For most cases, this will serve for the very same purpose of C♯'s null-coalescing operator, but keep in mind:If you use your variable
sto hold something that is either a reference to the instance of a class orNone(as long as your class does not define members__nonzero__()and__len__()), it is secure to use the same semantics as the null-coalescing operator.In fact, it may even be useful to have this side-effect of Python. Since you know what values evaluates to false, you can use this to trigger the default value without using
Nonespecifically (an error object, for example).In some languages this behavior is referred to as the Elvis operator.