Python:如果不是 val,vs 如果 val 是 None
问题描述
我一直以 if not value
的风格进行编码,但是,一些指南引起了我的注意,虽然这种风格有效,但它似乎有两个潜在的问题:
I've always coded in the style of if not value
, however, a few guides have brought to my attention that while this style works, it seems to have 2 potential problems:
- 它不完全可读;
if value is None
肯定更容易理解. - 这可能会在以后产生影响(并导致细微的错误),因为像
[]
和0
这样的东西也会评估为False
.
- It's not completely readable;
if value is None
is surely more understandable. - This can have implications later (and cause subtle bugs), since things like
[]
and0
will evaluate toFalse
as well.
我也开始将这个想法应用到其他比较中,例如:
I am also starting to apply this idea to other comparisons, such as:
if not value
vsif value is False
if not value
vsif value is []
if not value
vsif value is False
if not value
vsif value is []
列表也是如此......
And so goes the list...
问题是,你在原则上走了多远?在保证代码安全的同时,在哪里划清界限?
The question is, how far do you go with the principle? Where to draw the line, while keeping your code safe?
无论如何我都应该使用 if value is None
样式吗?
Should I always use the if value is None
style no matter what?
解决方案
如果你想要的话,使用与 None 的比较.使用如果不是价值"如果您只想检查该值是否被认为是假的(空列表,无,假).
Use a comparison to None if that's what you want. Use "if not value" if you just want to check if the value is considered false (empty list, none, false).
我发现如果不是价值"看起来更干净和 Pythonic.
I find "if not value" to be cleaner looking and Pythonic.
另外,请注意列表.在比较空列表时不应使用 is.如果你知道你得到一个列表,使用 if <list>
检查它是否有任何内容(或 len()).尝试在解释器中输入:
Also, be careful with lists. You should not use is when comparing for an empty list. If you know you're getting a list, use if <list>
to check if it has any contents (or len()). Try typing this into the interpreter:
>>> a = []
>>> a is []
False
这是因为您刚刚创建的临时列表在内存中的地址与存储在a"中的地址不同.你看不到这与 None、False 或 True 因为这些都是单例值(它们都引用内存的同一部分),所以使用 'is' 关键字有效.
This is because the temporary list you just made has a different address in memory than the one stored at 'a'. You don't see this with None, False, or True because these are all values that are singletons (they all refer to the same section of memory) so using the 'is' keyword works.
您还会发现 CPython 实习生字符串,因此以下工作.
You'll also find that CPython interns strings so the following works.
>>> 'a' is 'a'
True
你不应该依赖这个.这是一个实现细节,并没有指定适用于每个版本的 Python.
You should not rely on this. It is an implementation detail and this is not specified to work with every version of Python.
相关文章