"if x" 和 "if x is not None" 的区别

55

看起来 if x 几乎就像是 if x is not None 更长的简写语法。它们在功能上是完全相同的,还是在某些情况下对于给定的 x 值,两者会有不同的计算结果?

我认为这种行为在Python的各种实现中应该也是相同的,但如果有微妙的差异,那就很好了解。

5个回答

68

在以下情况下:

test = False 
test = "" 
test = 0
test = 0.0 
test = []
test = () 
test = {} 
test = set()

if语句中的if测试会有所不同:

if test: #False

if test is not None: #True 

这是因为is测试的是身份(identity),意味着

test is not None

等价于

id(test) == id(None) #False

因此

(test is not None) is (id(test) != id(None)) #True

3
甚至更多的情况下,所有空集合和0等价物(通常)都是假的。 - user395760
1
collections.deque,collections.defaultdict,collections.namedtuple,collections.OrderedDict...还有任何使用魔术方法__bool____nonzero__并返回false的内容。 - Autoplectic
1
并且要进一步解释0等效的内容:Decimal(0),0+0j,0.0等都会被评估为false。 - Autoplectic

37

前者测试真实性,而后者测试与None的身份是否相同。许多值为假,例如False0''None,但只有NoneNone

注:Trueness指的是一个值在布尔上下文中被认为是“真”的能力,而不是它的实际身份(如对象引用)。例如,非零数字在布尔上下文中被视为True,尽管它们的身份可能不同。


5
x = 0
if x: ...  # False
if x is not None: ... # True

5

if x 检查 x 是否被视为 True

在 Python 中,所有的值都有一个布尔值 (True/False)。

被视为 False 的值包括:

  • False, None
  • 0, 0.0, 0j
  • [], (), {}
  • ''
  • 其他向 Python 发送信号表示它们为空的实例

其他值被视为 True。例如,[False]('hello')'hello' 被视为 True (因为它们不是空的)。

当使用 if x is not None 时,您正在检查 x 是否不是 None,但它可能是 False 或其他被视为 False 的实例。

>>> x = None
>>> if not x:print x # bool(None) is False
None
>>> if x == None:print x
None
>>> x = False
>>> if not x:print x
False
>>> if x == None:print x

最后,请注意TrueFalse分别等于10

>>> True + 1
2
>>> False + 1
1
>>> range(1, 5)[False]
1

3
if x:
    # Evaluates for any defined non-False value of x
if not x:
    # Evaluates for any defined False value of x
if x is None:
    # Evaluates for any instances of None

None不是它自己的类型,它恰好等于False。"if not x" 语句只有在x=None时才会成立,因为None等同于False。

我不知道是否存在微妙的区别,但确实有一些精确的方法可以在特定情况下测试正/负性。在某些情况下混用它们可能有效,但如果不理解它们会导致问题。

if x is True:
    # Use for checking for literal instances of True
if x is False:
    # Use for checking for literal instances of False
if x is None:
    # Use for checking for literal instances of None
if x:
    # Use for checking for non-negative values
if not x:
    # Use for checking for negative values
    # 0, "", None, False, [], (), {} are negative, all others are True

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接