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

后端 未结 4 2018
时光说笑
时光说笑 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:59

    I wrote this function with your required behavior. An advantage of this over chaining and is that it's easier to write when it comes to long chains. Heads up this doesn't work with object keys, only attributes.

    def null_conditional(start, *chain):
        current = start
        for c in chain:
            current = getattr(current, c, None)
            if current is None:
                break
        return current
    

    Here's some tests I ran so you can see how it works

    class A(object):
        b = None
        def __init__(self, v):
            self.b = v
    
    class B(object):
        c = None
        def __init__(self, v):
            self.c = v    
    
    a_1 = A(B(2))
    a_2 = A(None)
    print(null_conditional(a_1, 'b', 'c')) # 2
    print(null_conditional(a_1, 'b', 'd')) # None
    print(null_conditional(a_2, 'b', 'c')) # None
    print(null_conditional(None, 'b')) # None
    print(null_conditional(None, None)) # TypeError: attribute name must be string
    

提交回复
热议问题