Python's equivalent to null-conditional operator introduced in C# 6

后端 未结 4 2000
时光说笑
时光说笑 2021-01-01 16:04

Is there an equivalent in Python to C# null-conditional operator?

System.Text.StringBuilder sb = null;
string s = sb?.ToString(); // No error
4条回答
  •  隐瞒了意图╮
    2021-01-01 16:45

    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.

提交回复
热议问题