在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)?
or?例如:
def my_function(arg_1=None, arg_2=0):
determination = arg_1 or arg_2 or 'no arguments given!'
print(determination)
return determination
Run Code Online (Sandbox Code Playgroud)
当没有参数调用时,上面的函数将打印并返回 'no arguments given!'
为什么Python会这样做,以及如何才能最好地利用此功能?
从中获取大量配置值时os.environ,在python代码中使用默认值可以轻松地允许应用程序在许多上下文中启动.典型的django settings.py有很多
SOME_SETTING = os.environ.get('SOME_SETTING')
Run Code Online (Sandbox Code Playgroud)
线.
为了提供合理的默认值,我们选择了
SOME_SETTING = os.environ.get('SOME_SETTING') or "theValue"
Run Code Online (Sandbox Code Playgroud)
但是,由于调用应用程序,这很容易出错
SOME_SETTING=""
Run Code Online (Sandbox Code Playgroud)
manage.py
将导致SOME_SETTING设置为theValue而不是明确定义""
有没有办法在python中使用三元组分配值a = b if b else d而不重复b或将其分配给速记变量?
如果我们看一下,这就变得很明显
SOME_VERY_LONG_VAR_NAME = os.environ.get('SOME_VERY_LONG_VAR_NAME') if os.environ.get('SOME_VERY_LONG_VAR_NAME') else 'meh'
Run Code Online (Sandbox Code Playgroud)
能够做类似的事情会好得多
SOME_VERY_LONG_VAR_NAME = if os.environ.get('SOME_VERY_LONG_VAR_NAME') else 'meh'
Run Code Online (Sandbox Code Playgroud)