Python 代码里同时出现 a == b 和 a is b 时,很多初学者会把它们都理解成“相等”。实际运行列表示例就能看出差异:- a = [1, 2, 3]
- b = [1, 2, 3]
- print(a == b) # True
- print(a is b) # False
复制代码 == 比较的是值,is 比较的是对象身份。可以把 == 理解成“两张钞票购买力是否相同”,把 is 理解成“是不是同一张钞票”。源码中反复强调的一点是:is 本质上等价于比较 id(a) 和 id(b),但它不能被重载;== 则会调用 __eq__,因此结果与类型实现有关。
一、用 id() 理解 is- a = [1, 2, 3]
- b = [1, 2, 3]
- c = a
- print(a is c) # True
- print(id(a) == id(c)) # True
- print(a is b) # False
- print(a == b) # True
复制代码 a 和 c 指向同一个列表对象,所以 a is c 为 True;b 是另一个列表对象,即使内容相同,a is b 仍为 False。实际编码中不建议用 id(a) == id(b) 替代 is,因为 id 可能在对象销毁后被复用,而且 is 是语法级操作,更直接也更符合 Python 风格。
二、== 调用 __eq__,并存在回退流程
表达式 a == b 首先尝试 a.__eq__(b)。列表、元组、字典、集合都有各自的比较规则:列表和元组逐元素比较,字典逐键值比较,集合比较内容且与顺序无关。自定义类可以通过 __eq__ 决定相等性:- class Person:
- def __init__(self, name, age):
- self.name = name
- self.age = age
- def __eq__(self, other):
- if not isinstance(other, Person):
- return False
- return self.name == other.name and self.age == other.age
- p1 = Person('小明', 25)
- p2 = Person('小明', 25)
- print(p1 == p2) # True
复制代码 如果类没有定义 __eq__,默认继承 object.__eq__,而 object.__eq__ 默认比较的就是身份。因此下面两个对象值字段相同,但 == 仍然为 False:- class Simple:
- def __init__(self, value):
- self.value = value
- s1 = Simple(10)
- s2 = Simple(10)
- s3 = s1
- print(s1 == s2) # False,默认比较身份
- print(s1 == s3) # True,同一个对象
复制代码 == 的完整流程还包含 NotImplemented 回退:先调用 a.__eq__(b),如果返回 NotImplemented,再尝试 b.__eq__(a);如果双方都返回 NotImplemented,才回退到 id 比较。源码给出如下实验:- class AlwaysNotImplemented:
- def __eq__(self, other):
- return NotImplemented
- class AlwaysTrueEquals:
- def __eq__(self, other):
- return True
- a = AlwaysNotImplemented()
- b = AlwaysTrueEquals()
- print(a == b) # True,a.__eq__ 回退到 b.__eq__
复制代码
三、is 不能被重载
Python 没有 __is__ 这类可重载方法。类可以重载 __eq__ 让 == 返回 True,但 is 仍然只比较对象身份:- class MyClass:
- def __eq__(self, other):
- return True
- obj1 = MyClass()
- obj2 = MyClass()
- print(obj1 == obj2) # True
- print(obj1 is obj2) # False
复制代码 这也是为什么判断 None 时优先用 is:它不会受到对象自定义 __eq__ 的干扰。
四、小整数缓存和字符串驻留是实现细节
Python 会预创建并复用 -5 到 256 之间的小整数,所以 256 is 256 通常为 True;257 不在缓存范围内,每次写 257 可能创建新对象:- a = 256
- b = 256
- print(a is b) # True
- a = 257
- b = 257
- print(a is b) # False
- a = 257; b = 257
- print(a is b) # 可能为 True,属于解释器优化,不要依赖
复制代码 字符串也存在驻留机制。简单字符串通常会被复用,动态拼接的字符串不一定:- a = 'hello'
- b = 'hello'
- print(a is b) # 通常 True
- c = 'hello' + 'world'
- d = 'helloworld'
- print(c is d) # 可能 False
- print(c == d) # True
复制代码 需要手动驻留时可以用 sys.intern:- import sys
- a = sys.intern('hello world ' + '!')
- b = sys.intern('hello world ' + '!')
- print(a is b) # True
复制代码 空元组 ()、None、True、False 都是单例,因此 is 比较通常为 True;小列表和字典不会被缓存,每次创建都是新对象。生产代码不要依赖整数缓存和字符串驻留,比较值一律用 ==。
五、什么时候必须用 is
最典型的规则是:和 None 比较永远用 is 或 is not。PEP 8 明确推荐这种写法。原因是 None 是单例,is 检查最精确、速度更快,而且不会被 __eq__ 重载影响。下面的例子说明 == 可能被对象欺骗:- class TrickyNone:
- def __eq__(self, other):
- return True
- x = TrickyNone()
- print(x == None) # True,但 x 显然不是 None
- print(x is None) # False
复制代码 其他适合用 is 的场景包括:判断哨兵对象、验证单例模式、检测链表环、判断缓存是否命中、区分“值为 None”和“未设置”。不要用 is 比较数值、字符串、列表、字典或集合内容,这些都应该用 ==。类型检查通常优先用 isinstance,而不是 type(obj) is int。
六、哨兵对象:区分 None 和未设置
当 None 本身是合法返回值时,不能用 None 当“未找到”的标记。源码中的做法是创建唯一 object() 作为哨兵,并用 is 判断:- _MISSING = object()
- _DELETED = object()
- class Cache:
- def __init__(self):
- self._data = {}
- def get(self, key, default=_MISSING):
- if key in self._data:
- value = self._data[key]
- if value is _DELETED:
- if default is _MISSING:
- raise KeyError(key)
- return default
- return value
- if default is _MISSING:
- raise KeyError(key)
- return default
- def delete(self, key):
- self._data[key] = _DELETED
- def set(self, key, value):
- self._data[key] = value
- cache = Cache()
- cache.set('name', None)
- cache.set('age', 25)
- cache.delete('age')
- print(cache.get('name')) # None,合法存储值
- print(cache.get('age', 'N/A')) # N/A,被删除
- print(cache.get('email', 'N/A')) # N/A,不存在
复制代码 这里 _MISSING 和 _DELETED 都用 object() 创建,每次创建都是独立对象,因此用 is 判断不会与用户数据混淆。
七、单例模式和链表环检测
单例模式中,is 用来验证两个变量是否指向同一个实例:- class AppConfig:
- _instance = None
- def __new__(cls):
- if cls._instance is None:
- cls._instance = super().__new__(cls)
- cls._instance._initialized = False
- return cls._instance
- def __init__(self):
- if self._initialized:
- return
- self.config = {}
- self._initialized = True
- def load(self, **kwargs):
- self.config.update(kwargs)
- config1 = AppConfig()
- config2 = AppConfig()
- print(config1 is config2) # True
- config1.load(host='localhost', port=8080)
- print(config2.config) # 能看到 config1 的设置
复制代码 链表环检测是 is 的经典算法场景。快慢指针相遇时,关心的是“是否指向同一个节点对象”,不是节点值是否相等:- class Node:
- def __init__(self, value):
- self.value = value
- self.next = None
- def has_cycle(head):
- if head is None:
- return False
- slow = head
- fast = head
- while fast is not None and fast.next is not None:
- slow = slow.next
- fast = fast.next.next
- if slow is fast:
- return True
- return False
- n1 = Node(1)
- n2 = Node(2)
- n3 = Node(3)
- n4 = Node(4)
- n1.next = n2
- n2.next = n3
- n3.next = n4
- n4.next = n2
- print(has_cycle(n1)) # True
复制代码 缓存装饰器也可以用哨兵区分“结果为 None”和“未缓存”:- class CacheDecorator:
- def __init__(self):
- self._cache = {}
- self._NOT_CACHED = object()
- def cached_call(self, func, *args):
- key = (func.__name__, args)
- result = self._cache.get(key, self._NOT_CACHED)
- if result is self._NOT_CACHED:
- result = func(*args)
- self._cache[key] = result
- return result
复制代码
八、常见陷阱
第一,不要用 is 比较整数值。if code is 200 依赖小整数缓存,看似能运行,但属于不可靠实现细节,应改为 code == 200。第二,不要用 is 比较字符串。username is 'admin' 在动态拼接、文件读取、网络输入等场景下通常会失败,应改为 username == 'admin'。第三,is not 和 not (x is None) 等价,但推荐写 x is not None;不要写成 x is (not None)。第四,nan 的比较很特殊,nan == nan 为 False,nan is nan 为 True,检查 nan 应使用 math.isnan。- import math
- nan = float('nan')
- print(nan == nan) # False
- print(nan is nan) # True
- print(math.isnan(nan)) # True
复制代码 第五,可变对象的 == 结果可能随内容变化,is 结果只跟身份有关:- lst1 = [1, 2, 3]
- lst2 = [1, 2, 3]
- lst3 = lst1
- print(lst1 == lst2) # True
- print(lst1 is lst3) # True
- lst1.append(4)
- print(lst1 == lst2) # False,值变了
- print(lst1 is lst3) # True,身份没变
复制代码
速查结论:和 None 比较用 is;比较数值、字符串、列表、字典、集合内容用 ==;单例验证、哨兵对象检测、链表节点相遇判断用 is;类型检查优先 isinstance。理解 == 调用 __eq__、is 比较身份,以及小整数缓存和字符串驻留只是实现细节,就能避免大多数 Python 相等性判断问题。 |