问题描述
我必须从一个变量中提取值,该变量可能是None,记住一些默认值。我第一次写下代码:
I have to extract values from a variable that may be None, with some defaults in mind. I first wrote this code:
if self.maxTiles is None:
maxX, maxY = 2, 2
else:
maxX, maxY = self.maxTiles
然后我意识到我可以缩短它:
Then I realized I could shorten it to:
maxX, maxY = self.maxTiles if self.maxTiles is not None else (2, 2)
但是我意识到这可能是最简洁和容易阅读的:
But then I realized this might be the most succinct and easily readable:
maxX, maxY = self.maxTiles or (2, 2)
推荐答案
关于,具体来说,
self.maxTiles if self.maxTiles is not None else (2, 2)
我发现一般形式的双重否定如果不是A:B else:C
语句或表达式)可能相当混乱/误导;这不是字面上的如果没有... else
,但移动不是
不会使双负
I've found that "double negatives" of the general form if not A: B else: C
(whether as statements or expressions) can be quite confusing / misleading; this isn't literally an if not .. else
, but moving the not
doesn't make the "double negative" go away.
因此,一般来说,如果A:C else:B 。在这种特殊情况下,如果我选择三元运算符形式,我将它编码为
So, in general, I just rewrite such constructs to if A: C else: B
. In this particular case, if I did choose the ternary-operator form, I'd code it as
(2, 2) if self.maxTiles is None else self.maxTiles
对于更一般的问题: a = b或c
很好当且仅当你真的想使用 c
b
的任何假值 c> 无
。 IOW, b或c
是更好的表达方式。
On to the more general question: a = b or c
is fine if and only if you really want to use c
for any false value of b
-- it's not fine to deal specifically with b
being None
. IOW, b or c
is a better way to express
b if b else c
但是不是核心测试是, b是None
。在理论上,如果你知道 b
的唯一可能的假值是 None
,它们在语义上是等价的,但是强的只有可能的假值约束对你的代码的读者/维护者不会是明显的 - 如果你必须添加一个注释来解释,任何简单的优点或
可能声明被废除...更好的是,如果可行,在代码中说,而不是让代码是晦涩的,需要评论,以澄清什么它在做什么和什么时候(意见,真正有用的是那些解释,而不是什么和什么时候[[代码本身应该显示!)]],而是为什么当它不明显 - 这个特定的应用程序目的是什么代码功能的tidbit)。
but it's not a way to express a similar expression where the core test is, instead, b is None
. In theory, if you "know" that the only possible false value for b
is None
, they're semantically equivalent, but that strong "only possible false value" constraint will not be apparent to readers / maintainers of your code -- and if you have to add a comment to explain that, any conciseness advantages that or
might claim are nullified... better, when feasible, to "say it in code", rather than have the code be obscure and need comments to clarify exactly what it's doing and when (comments that are really useful are rather those which explain, not the what and the when [[the code itself should show that!-)]], but rather the why when it's not obvious -- what's the application purpose being served by this specific tidbit of code functionality).
这篇关于x或y:可接受的成语,或混淆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!