比較是 vs

一個常見的陷阱是混淆了相等比較運算子 is==

a == b 比較 ab 的值。

a is b 將比較 ab身份

為了顯示:

a = 'Python is fun!'
b = 'Python is fun!'
a == b # returns True
a is b # returns False

a = [1, 2, 3, 4, 5]
b = a      # b references a
a == b     # True
a is b     # True
b = a[:]   # b now references a copy of a
a == b     # True
a is b     # False [!!]

基本上,is 可以被認為是 id(a) == id(b) 的簡寫。

除此之外,執行時環境的怪癖使事情進一步複雜化。由於 Python 機器試圖為相同的物件使用更少的記憶體,因此與 is 相比,短字串和小整數將返回 True

a = 'short'
b = 'short'
c = 5
d = 5
a is b # True
c is d # True

但是較長的字串和較大的整數將分開儲存。

a = 'not so short'
b = 'not so short'
c = 1000
d = 1000
a is b # False
c is d # False

你應該使用 is 來測試 None

if myvar is not None:
    # not None
    pass
if myvar is None:
    # None
    pass

is 的用途是測試哨兵(即一個獨特的物體)。

sentinel = object()
def myfunc(var=sentinel):
    if var is sentinel:
        # value wasn’t provided
        pass
    else:
        # value was provided
        pass