一个班轮“如果不是无则分配”

Don*_*lon 11 python null-coalescing-operator python-3.x

有没有办法只在分配的值不是 None 时才进行分配,否则什么都不做?

我们当然可以这样做:

x = get_value() if get_value() is not None
Run Code Online (Sandbox Code Playgroud)

但这将读取该值两次。我们可以将它缓存到一个局部变量中:

v = get_value()
x = v if v is not None
Run Code Online (Sandbox Code Playgroud)

但现在我们为一件简单的事情做了两个陈述。

我们可以写一个函数:

def return_if_not_none(v, default):
    if v is not None:
        return v
    else:
        return default
Run Code Online (Sandbox Code Playgroud)

然后做x = return_if_not_none(get_value(), x)。但是肯定已经有一个 Python 习惯用法可以实现这一点,无需访问xget_value()两次,也无需创建变量?

换句话说,假设=??是一个类似于C# null 合并运算符的 Python 运算。与 C# 不同??=,我们虚构的运算符检查右侧是否为None

x = 1
y = 2
z = None

x =?? y
print(x)   # Prints "2"

x =?? z
print(x)   # Still prints "2"
Run Code Online (Sandbox Code Playgroud)

这样的=??操作员会完全按照我的问题进行操作。

ale*_*07v 14

在python 3.8中你可以做这样的事情

if (v := get_value()) is not None:
    x = v
Run Code Online (Sandbox Code Playgroud)

基于 Ryan Haining 解决方案更新,见评论

  • `if (v := get_value()) is not None): x = v` (3认同)