2011-02-12 44 views
163

在C#中有一个null-coalescing operator(写为??),可实现简单的(短)空检查分配期间:是否存在与C#空合并运算符相当的Python?

string s = null; 
var other = s ?? "some default value"; 

有没有一个python等效?

我知道我能做到:

s = None 
other = s if s else "some default value" 

但有一个更短的方式(这里我不需要重复s)?

+5

````操作符被建议为[PEP 505](https://www.python.org/dev/peps/pep-0505/)。 – 2016-10-20 18:39:17

回答

248
other = s or "some default value" 

好的,必须澄清or运营商是如何工作的。它是一个布尔运算符,因此它在布尔上下文中工作。如果这些值不是布尔值,则为了操作员的目的将它们转换为布尔值。

请注意,or运营商不只返回TrueFalse。相反,如果第一个操作数的计算结果为true,则返回第一个操作数;如果第一个操作数的计算结果为false,则返回第二个操作数。

在这种情况下,表达式x or y返回x如果它是True或者转换为布尔值时返回true。否则,它返回y。在大多数情况下,这将有助于为C♯的空合并运算的同样的目的,但要记住:

42 or "something" # returns 42 
0  or "something" # returns "something" 
None or "something" # returns "something" 
False or "something" # returns "something" 
"" or "something" # returns "something" 

如果您使用的变量s持有的东西,或者是给一个参考一个类的实例或None(只要你的类没有定义成员__nonzero__()__len__()),则使用与空合并运算符相同的语义是安全的。

事实上,Python的这种副作用甚至可能是有用的。由于您知道哪些值的计算结果为false,因此您可以使用它来触发默认值,而不使用None(例如,错误对象)。

在某些语言中,此行为被称为Elvis operator

+3

这个工作是否一样?我的意思是,如果's`是一个有效值但不是真的,它会破坏吗? (我不知道Python,所以我不确定'truthy'的概念是否适用。) – cHao 2011-02-12 15:33:42

+6

除了常量“0”,“None”和空容器(包括字符串)返回FALSE。其他大部分事情都被视为真实。我想说,这里的主要危险是你会得到一个真正的但没有字符串的值,但这在某些程序中不会成为问题。 – kindall 2011-02-12 15:52:58

+15

如果s是None **或False **,则使用此_other_将获得默认值,这可能不是所期望的。 – pafcu 2011-02-12 16:15:22

38

严格,

other = s if s is not None else "default value" 

否则S = false将成为 “默认值”,这可能不是想要的结果。

如果你想使这个更短,尽量

def notNone(s,d): 
    if s is None: 
     return d 
    else: 
     return s 

other = notNone(s, "default value") 
25

这里将返回不是无的第一个参数的函数:

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) 

减少()可能不必要地遍历所有参数即使第一个参数不是None,所以你也可以使用这个版本:

def coalesce(*arg): 
    for el in arg: 
    if el is not None: 
     return el 
    return None 
1

In add银行足球比赛到利亚诺的关于“或”行为答案: 它的“快”

>>> 1 or 5/0 
1 

所以有时它可能是东西有用的快捷方式一样

object = getCachedVersion() or getFromDB() 
-3

两个功能下我已经发现处理很多变量测试时非常有用。

def nz(value, none_value, strict=True): 
    ''' This function is named after an old VBA function. It returns a default 
     value if the passed in value is None. If strict is False it will 
     treat an empty string as None as well. 

     example: 
     x = None 
     nz(x,"hello") 
     --> "hello" 
     nz(x,"") 
     --> "" 
     y = "" 
     nz(y,"hello") 
     --> "" 
     nz(y,"hello", False) 
     --> "hello" ''' 

    if value is None and strict: 
     return_val = none_value 
    elif strict and value is not None: 
     return_val = value 
    elif not strict and not is_not_null(value): 
     return_val = none_value 
    else: 
     return_val = value 
    return return_val 

def is_not_null(value): 
    ''' test for None and empty string ''' 
    return value is not None and len(str(value)) > 0 
相关问题