Kla*_*sen 258 python null-coalescing-operator
在C#中有一个null-coalescing运算符(写为??),允许在赋值期间进行简单(短)空检查:
string s = null;
var other = s ?? "some default value";
Run Code Online (Sandbox Code Playgroud)
是否有python等价物?
我知道我能做到:
s = None
other = s if s else "some default value"
Run Code Online (Sandbox Code Playgroud)
但是有更短的方式(我不需要重复s)?
Jul*_*ano 372
other = s or "some default value"
Run Code Online (Sandbox Code Playgroud)
好的,必须澄清or操作员的工作原理.它是一个布尔运算符,因此它在布尔上下文中工作.如果值不是布尔值,则为运算符的目的将它们转换为布尔值.
请注意,or操作员不会仅返回True或False.相反,如果第一个操作数的计算结果为true,则返回第一个操作数;如果第一个操作数的计算结果为false,则返回第二个操作数.
在这种情况下,表达式x or y返回,x如果是,True或者在转换为boolean时求值为true.否则,它返回y.对于大多数情况,这将用于C♯的null-coalescing运算符的相同目的,但请记住:
42 or "something" # returns 42
0 or "something" # returns "something"
None or "something" # returns "something"
False or "something" # returns "something"
"" or "something" # returns "something"
Run Code Online (Sandbox Code Playgroud)
如果你使用你的变量s来保存一个对类实例的引用或者None(只要你的类没有定义成员__nonzero__()和__len__()),那么使用与null-coalescing运算符相同的语义是安全的.
实际上,拥有Python的这种副作用甚至可能是有用的.由于您知道哪些值的计算结果为false,因此您可以使用它来触发默认值而不使用None特定的值(例如,错误对象).
在某些语言中,此行为称为Elvis运算符.
Hug*_*ell 54
严格,
other = s if s is not None else "default value"
Run Code Online (Sandbox Code Playgroud)
否则s = False将成为"默认值",这可能不是预期的.
如果你想缩短它,试试吧
def notNone(s,d):
if s is None:
return d
else:
return s
other = notNone(s, "default value")
Run Code Online (Sandbox Code Playgroud)
mor*_*ehu 39
这是一个函数,它将返回第一个不是None的参数:
def coalesce(*arg):
return reduce(lambda x, y: x if x is not None else y, arg)
# Prints "banana"
print coalesce(None, "banana", "phone", None)
Run Code Online (Sandbox Code Playgroud)
即使第一个参数不是None,reduce()也可能会不必要地遍历所有参数,因此您也可以使用此版本:
def coalesce(*arg):
for el in arg:
if el is not None:
return el
return None
Run Code Online (Sandbox Code Playgroud)
Hen*_*huy 11
除了@Bothwells答案(我更喜欢)对于单个值之外,为了对函数返回值进行空检查分配,您可以使用新的海象运算符(自python3.8起):
def test():
return
a = 2 if (x:= test()) is None else x
Run Code Online (Sandbox Code Playgroud)
因此,test函数不需要计算两次(如a = 2 if test() is None else test())
Cra*_*aig 10
我意识到这已经得到了回答,但是在处理对象时还有另一种选择。
如果您的对象可能是:
{
name: {
first: "John",
last: "Doe"
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用:
obj.get(property_name, value_if_null)
Run Code Online (Sandbox Code Playgroud)
喜欢:
obj.get("name", {}).get("first", "Name is missing")
Run Code Online (Sandbox Code Playgroud)
通过添加{}作为默认值,如果缺少“name”,则返回一个空对象并传递给下一个 get。这类似于 C# 中的空安全导航,类似于obj?.name?.first.
如果您需要嵌套多个空合并操作,例如:
model?.data()?.first()
这不是一个容易解决的问题or。它也无法解决.get()需要字典类型或类似类型(并且无论如何都不能嵌套)或者getattr()当 NoneType 没有该属性时会抛出异常的问题。
考虑向语言添加空值合并的相关 pip 是PEP 505,与文档相关的讨论在python-ideas线程中。
| 归档时间: |
|
| 查看次数: |
69067 次 |
| 最近记录: |