简体   繁体   English

在 Python 中,'foo = x 或“默认”' 是否正确?

[英]In Python, is 'foo = x or "default"' correct?

In javascript, foo = x || "default"在javascript中, foo = x || "default" foo = x || "default" is often coded. foo = x || "default"通常被编码。 If x = null , foo = "default" .如果x = nullfoo = "default"

In python, is foo = x or "default" correct?在 python 中, foo = x or "default"是否正确?

Your code as written will produce the behavior you describe, but I would suggest the following, which is the Python canonical form of a ternary expression您编写的代码将产生您描述的行为,但我建议以下内容,这是三元表达式Python 规范形式

>>> x = None
>>> foo = x if x else 'default'
>>> foo
'default'

If you are familiar with C++, you can read the above as if it were the below ternary expression如果你熟悉C++,你可以把上面的内容当成下面的三元表达式来阅读

foo = x ? x : "default";

Yes, it works.是的,它有效。 From documentation -文档 -

The expression x and y first evaluates x ;表达式x and y首先计算x if x is false , its value is returned;如果xfalse ,则返回其值; otherwise, y is evaluated and the resulting value is returned.否则,计算y并返回结果值。

The expression x or y first evaluates x ;表达式x or y首先计算x if x is true , its value is returned;如果 x 为true ,则返回其值; otherwise, y is evaluated and the resulting value is returned.否则,计算y并返回结果值。

(Note that neither and nor or restrict the value and type they return to False and True , but rather return the last evaluated argument. This is sometimes useful, eg, if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value. (请注意,无论是and也不or限制值并键入他们返回FalseTrue ,而是返回最后一个变量,这有时是有用的,例如,如果s是应该由一个默认值来代替,如果它是一个字符串为空,表达式s or 'foo'产生所需的值。

(Emphasis mine) (强调我的)

Please note when you do -请注意,当你这样做 -

foo = x or "default"

if x is None or empty string, in both cases "default" would be the return value of the expression - x or "default" .如果xNone或空字符串,在这两种情况下, "default"将是表达式的返回值 - x or "default"

It is 'correct'/valid code (as long as x is defined), but bear in mind that foo will be set to "default" for any falsy value such as 0 , "" , [] or {} .它是“正确”/有效代码(只要定义了x ),但请记住,对于任何虚假值,例如0""[]{}foo将被设置为"default"

If you only want to use the default value if x is not None , you can use: foo = x if x is not None else "default"如果您只想在x不是None使用默认值,则可以使用: foo = x if x is not None else "default"

This is demonstrated below.这在下面被证明。

x = 0
print(x if x is not None else "default")  # prints 0
print(x or "default")  # prints default

If you are defining a function, you will probably just want to use default parameters.如果您正在定义一个函数,您可能只想使用默认参数。

Again, demonstrated below:再次证明如下:

def myfunc(x="default"):
    print(x)

myfunc()  # prints default
myfunc("custom value")  # prints custom value

If by "correct", you mean "does it work?", then yes, it is correct.如果“正确”是指“它有效吗?”,那么是的,它是正确的。 It works fine and will work as you expect it to.它工作正常,并且会按您的预期工作。 Note, however, that if x is something like False , 0 , None , or "" , foo will also be set to default due to the way boolean logic works in Python.但是请注意,如果xFalse0None"" default由于布尔逻辑在 Python 中的工作方式, foo也将设置为default值。

If by "correct", you mean "is it correct conventions?", then yes, I would also say it is correct.如果“正确”是指“这是正确的约定吗?”,那么是的,我也会说它是正确的。 This is a common pattern that I have seen many developers use throughout several projects.这是我在多个项目中看到许多开发人员使用的常见模式。 It is also given as an example in the Python documentation.它也在 Python 文档中作为示例给出。

The code works fine if x is already defined, else you will get an error.如果x已经定义,代码工作正常,否则你会得到一个错误。

Correct usage:正确用法:

 >>> x= None
 >>> foo = x or "default"
 >>> foo
 'default'

Error case :错误情况:

>>> foo = x or "default"

Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    foo = x or "default"
NameError: name 'x' is not defined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM