在c#中,有一个空合并操作符(写为??),允许在赋值时简单(短)检查空值:

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

python中有等效的吗?

我知道我能做到:

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

但是有没有更短的方法(我不需要重复s)?


当前回答

除了Juliano关于“或”行为的回答之外: 这是“快速”

>>> 1 or 5/0
1

有时候这可能是一个有用的快捷方式

object = getCachedVersion() or getFromDB()

其他回答

处理可能的异常:

def default_val(expr, default=None):
    try:
        tmp = expr()
    except Exception:
        tmp = default
    return tmp

像这样使用它:

default_val(lambda: some['complex'].expression('with', 'possible')['exceptions'], '')

下面是一个函数,它将返回第一个非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)

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

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

我知道这是有答案的,但是当您处理类似字典的对象时,还有另一种选择。

如果你有一个对象可能是:

{
   name: {
      first: "John",
      last: "Doe"
   }
}

你可以使用:

obj.get(property_name, value_if_null)

如:

obj.get("name", {}).get("first", "Name is missing") 

通过添加{}作为默认值,如果“name”缺失,则返回一个空对象并传递给下一个get。这类似于c#中的null-safe-navigation,类似于obj?.name?.first。

除了Juliano关于“或”行为的回答之外: 这是“快速”

>>> 1 or 5/0
1

有时候这可能是一个有用的快捷方式

object = getCachedVersion() or getFromDB()

严格来说,

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")