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

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

python中有等效的吗?

我知道我能做到:

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

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


当前回答

对于那些像我一样跌跌撞撞地在这里寻找一个可行的解决方案,当变量可能是未定义的,我得到的最接近的是:

if 'variablename' in globals() and ((variablename or False) == True):
  print('variable exists and it\'s true')
else:
  print('variable doesn\'t exist, or it\'s false')

请注意,签入全局变量时需要字符串,但之后在检查value时使用实际变量。

关于变量存在的更多信息: 如何检查变量是否存在?

其他回答

如果你需要链接多个空条件操作,例如:

. data()模型?当代()

这不是一个容易解决的问题。它也不能用.get()来解决,因为它需要字典类型或类似的类型(并且无论如何都不能嵌套),也不能用getattr()来解决,当NoneType没有属性时,getattr()会抛出异常。

考虑向语言中添加空合并的相关PEP是PEP 505,与该文档相关的讨论在python-ideas线程中。

我发现下面的两个函数在处理许多可变测试用例时非常有用。

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

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

对于那些像我一样跌跌撞撞地在这里寻找一个可行的解决方案,当变量可能是未定义的,我得到的最接近的是:

if 'variablename' in globals() and ((variablename or False) == True):
  print('variable exists and it\'s true')
else:
  print('variable doesn\'t exist, or it\'s false')

请注意,签入全局变量时需要字符串,但之后在检查value时使用实际变量。

关于变量存在的更多信息: 如何检查变量是否存在?