Is there an equivalent in Python to C# null-conditional operator?
System.Text.StringBuilder sb = null;
string s = sb?.ToString(); // No error
Well, the simplest solution would be:
result = None if obj is None else obj.method()
But if you want the exact equivalent having the same thread safety as the C#'s Null-conditional operator, it would be:
obj = 'hello'
temp = obj
result = None if temp is None else temp.split()
The trade off is that the code isn't really pretty; Also an extra name temp
gets added to the namespace.
Another way is:
def getattr_safe(obj, attr):
return None if obj is None else getattr(obj,attr)
obj = 'hello'
result = getattr_safe(obj,'split')()
Here, trade-off is the function calling overhead, but much clearer code, especially if you are using it multiple times.