python - 一个类轮到 "assign if not None"

标签 python python-3.x null-coalescing-operator

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

我们当然可以这样做:

x = get_value() if get_value() is not None

但这将读取该值两次。我们可以将它缓存到一个局部变量中:
v = get_value()
x = v if v is not None

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

我们可以写一个函数:
def return_if_not_none(v, default):
    if v is not None:
        return v
    else:
        return default

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

换句话说,让我们说 =??是类似于 C# null coalesce operator 的 Python 运算符.不像 C# ??= ,我们虚构的运算符检查右侧是否为 None :
x = 1
y = 2
z = None

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

x =?? z
print(x)   # Still prints "2"

这样的=??运算符(operator)将完全按照我的问题进行操作。

最佳答案

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

if (v := get_value()) is not None:
    x = v

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

关于python - 一个类轮到 "assign if not None",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59780089/

相关文章:

python - 有没有像 railsapi.com 这样好的 Python 文档浏览器

python - 如何在pygame中添加闪烁的光标?

javascript null 条件表达式

java - java 中的 c# null 合并运算符是否相等?

python - 如何从文件创建嵌套字典列表

c# - 使用 C#7 的 foreach 声明中的空合并运算符

python - 基于 PyQt 的 GUI 中的计时器

python:打印十六进制数据而不是字典

python - 输入 0 与层 conv2d_121 : expected ndim=4, 发现 ndim=5 不兼容

python - 如何使用 Python 在 Ubuntu 中创建自己的命令