查看: 508|回复: 3

Python中is与==区别:整数缓存、None比较与哨兵对象

[复制链接]
发表于 7 小时前 | 显示全部楼层 |阅读模式
Python 代码里同时出现 a == b 和 a is b 时,很多初学者会把它们都理解成“相等”。实际运行列表示例就能看出差异:
  1. a = [1, 2, 3]
  2. b = [1, 2, 3]
  3. print(a == b)  # True
  4. print(a is b)  # False
复制代码
== 比较的是值,is 比较的是对象身份。可以把 == 理解成“两张钞票购买力是否相同”,把 is 理解成“是不是同一张钞票”。源码中反复强调的一点是:is 本质上等价于比较 id(a) 和 id(b),但它不能被重载;== 则会调用 __eq__,因此结果与类型实现有关。

一、用 id() 理解 is
  1. a = [1, 2, 3]
  2. b = [1, 2, 3]
  3. c = a
  4. print(a is c)          # True
  5. print(id(a) == id(c))  # True
  6. print(a is b)          # False
  7. 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__ 决定相等性:
  1. class Person:
  2.     def __init__(self, name, age):
  3.         self.name = name
  4.         self.age = age
  5.     def __eq__(self, other):
  6.         if not isinstance(other, Person):
  7.             return False
  8.         return self.name == other.name and self.age == other.age
  9. p1 = Person('小明', 25)
  10. p2 = Person('小明', 25)
  11. print(p1 == p2)  # True
复制代码
如果类没有定义 __eq__,默认继承 object.__eq__,而 object.__eq__ 默认比较的就是身份。因此下面两个对象值字段相同,但 == 仍然为 False:
  1. class Simple:
  2.     def __init__(self, value):
  3.         self.value = value
  4. s1 = Simple(10)
  5. s2 = Simple(10)
  6. s3 = s1
  7. print(s1 == s2)  # False,默认比较身份
  8. print(s1 == s3)  # True,同一个对象
复制代码
== 的完整流程还包含 NotImplemented 回退:先调用 a.__eq__(b),如果返回 NotImplemented,再尝试 b.__eq__(a);如果双方都返回 NotImplemented,才回退到 id 比较。源码给出如下实验:
  1. class AlwaysNotImplemented:
  2.     def __eq__(self, other):
  3.         return NotImplemented
  4. class AlwaysTrueEquals:
  5.     def __eq__(self, other):
  6.         return True
  7. a = AlwaysNotImplemented()
  8. b = AlwaysTrueEquals()
  9. print(a == b)  # True,a.__eq__ 回退到 b.__eq__
复制代码

三、is 不能被重载
Python 没有 __is__ 这类可重载方法。类可以重载 __eq__ 让 == 返回 True,但 is 仍然只比较对象身份:
  1. class MyClass:
  2.     def __eq__(self, other):
  3.         return True
  4. obj1 = MyClass()
  5. obj2 = MyClass()
  6. print(obj1 == obj2)  # True
  7. print(obj1 is obj2)  # False
复制代码
这也是为什么判断 None 时优先用 is:它不会受到对象自定义 __eq__ 的干扰。

四、小整数缓存和字符串驻留是实现细节
Python 会预创建并复用 -5 到 256 之间的小整数,所以 256 is 256 通常为 True;257 不在缓存范围内,每次写 257 可能创建新对象:
  1. a = 256
  2. b = 256
  3. print(a is b)  # True
  4. a = 257
  5. b = 257
  6. print(a is b)  # False
  7. a = 257; b = 257
  8. print(a is b)  # 可能为 True,属于解释器优化,不要依赖
复制代码
字符串也存在驻留机制。简单字符串通常会被复用,动态拼接的字符串不一定:
  1. a = 'hello'
  2. b = 'hello'
  3. print(a is b)  # 通常 True
  4. c = 'hello' + 'world'
  5. d = 'helloworld'
  6. print(c is d)  # 可能 False
  7. print(c == d)  # True
复制代码
需要手动驻留时可以用 sys.intern:
  1. import sys
  2. a = sys.intern('hello world ' + '!')
  3. b = sys.intern('hello world ' + '!')
  4. print(a is b)  # True
复制代码
空元组 ()、None、True、False 都是单例,因此 is 比较通常为 True;小列表和字典不会被缓存,每次创建都是新对象。生产代码不要依赖整数缓存和字符串驻留,比较值一律用 ==。

五、什么时候必须用 is
最典型的规则是:和 None 比较永远用 is 或 is not。PEP 8 明确推荐这种写法。原因是 None 是单例,is 检查最精确、速度更快,而且不会被 __eq__ 重载影响。下面的例子说明 == 可能被对象欺骗:
  1. class TrickyNone:
  2.     def __eq__(self, other):
  3.         return True
  4. x = TrickyNone()
  5. print(x == None)  # True,但 x 显然不是 None
  6. print(x is None)  # False
复制代码
其他适合用 is 的场景包括:判断哨兵对象、验证单例模式、检测链表环、判断缓存是否命中、区分“值为 None”和“未设置”。不要用 is 比较数值、字符串、列表、字典或集合内容,这些都应该用 ==。类型检查通常优先用 isinstance,而不是 type(obj) is int。

六、哨兵对象:区分 None 和未设置
当 None 本身是合法返回值时,不能用 None 当“未找到”的标记。源码中的做法是创建唯一 object() 作为哨兵,并用 is 判断:
  1. _MISSING = object()
  2. _DELETED = object()
  3. class Cache:
  4.     def __init__(self):
  5.         self._data = {}
  6.     def get(self, key, default=_MISSING):
  7.         if key in self._data:
  8.             value = self._data[key]
  9.             if value is _DELETED:
  10.                 if default is _MISSING:
  11.                     raise KeyError(key)
  12.                 return default
  13.             return value
  14.         if default is _MISSING:
  15.             raise KeyError(key)
  16.         return default
  17.     def delete(self, key):
  18.         self._data[key] = _DELETED
  19.     def set(self, key, value):
  20.         self._data[key] = value
  21. cache = Cache()
  22. cache.set('name', None)
  23. cache.set('age', 25)
  24. cache.delete('age')
  25. print(cache.get('name'))          # None,合法存储值
  26. print(cache.get('age', 'N/A'))    # N/A,被删除
  27. print(cache.get('email', 'N/A'))  # N/A,不存在
复制代码
这里 _MISSING 和 _DELETED 都用 object() 创建,每次创建都是独立对象,因此用 is 判断不会与用户数据混淆。

七、单例模式和链表环检测
单例模式中,is 用来验证两个变量是否指向同一个实例:
  1. class AppConfig:
  2.     _instance = None
  3.     def __new__(cls):
  4.         if cls._instance is None:
  5.             cls._instance = super().__new__(cls)
  6.             cls._instance._initialized = False
  7.         return cls._instance
  8.     def __init__(self):
  9.         if self._initialized:
  10.             return
  11.         self.config = {}
  12.         self._initialized = True
  13.     def load(self, **kwargs):
  14.         self.config.update(kwargs)
  15. config1 = AppConfig()
  16. config2 = AppConfig()
  17. print(config1 is config2)  # True
  18. config1.load(host='localhost', port=8080)
  19. print(config2.config)  # 能看到 config1 的设置
复制代码
链表环检测是 is 的经典算法场景。快慢指针相遇时,关心的是“是否指向同一个节点对象”,不是节点值是否相等:
  1. class Node:
  2.     def __init__(self, value):
  3.         self.value = value
  4.         self.next = None
  5. def has_cycle(head):
  6.     if head is None:
  7.         return False
  8.     slow = head
  9.     fast = head
  10.     while fast is not None and fast.next is not None:
  11.         slow = slow.next
  12.         fast = fast.next.next
  13.         if slow is fast:
  14.             return True
  15.     return False
  16. n1 = Node(1)
  17. n2 = Node(2)
  18. n3 = Node(3)
  19. n4 = Node(4)
  20. n1.next = n2
  21. n2.next = n3
  22. n3.next = n4
  23. n4.next = n2
  24. print(has_cycle(n1))  # True
复制代码
缓存装饰器也可以用哨兵区分“结果为 None”和“未缓存”:
  1. class CacheDecorator:
  2.     def __init__(self):
  3.         self._cache = {}
  4.         self._NOT_CACHED = object()
  5.     def cached_call(self, func, *args):
  6.         key = (func.__name__, args)
  7.         result = self._cache.get(key, self._NOT_CACHED)
  8.         if result is self._NOT_CACHED:
  9.             result = func(*args)
  10.             self._cache[key] = result
  11.         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。
  1. import math
  2. nan = float('nan')
  3. print(nan == nan)       # False
  4. print(nan is nan)       # True
  5. print(math.isnan(nan))  # True
复制代码
第五,可变对象的 == 结果可能随内容变化,is 结果只跟身份有关:
  1. lst1 = [1, 2, 3]
  2. lst2 = [1, 2, 3]
  3. lst3 = lst1
  4. print(lst1 == lst2)  # True
  5. print(lst1 is lst3)  # True
  6. lst1.append(4)
  7. print(lst1 == lst2)  # False,值变了
  8. print(lst1 is lst3)  # True,身份没变
复制代码

速查结论:和 None 比较用 is;比较数值、字符串、列表、字典、集合内容用 ==;单例验证、哨兵对象检测、链表节点相遇判断用 is;类型检查优先 isinstance。理解 == 调用 __eq__、is 比较身份,以及小整数缓存和字符串驻留只是实现细节,就能避免大多数 Python 相等性判断问题。
回复

使用道具 举报

发表于 7 小时前 | 显示全部楼层

Re: Python中is与==区别:整数缓存、None比较与哨兵对象

这篇讲得很清楚,例子也很直观。== 比较值、is 比较对象身份这个核心点,加上 id、__eq__ 和 NotImplemented 回退流程,基本把容易混淆的地方都串起来了。小整数缓存和字符串驻留那部分也提醒得很及时,这些属于实现细节,生产代码里比较值还是老老实实用 ==,不要依赖缓存结果。和 None 比较用 is、哨兵对象用 is 这几条也很实用,尤其那个 __eq__ 返回 True 导致 x == None 为 True 的例子,确实能说明为什么不能随便用 == 判断 None。感谢整理。
回复 支持 反对

使用道具 举报

发表于 7 小时前 | 显示全部楼层

Re: Python中is与==区别:整数缓存、None比较与哨兵对象

这篇整理得很系统,尤其把 `==` 的 `__eq__` 调用和 `NotImplemented` 回退流程讲清楚了,这部分很多人平时只会说“比较值”,但真遇到自定义类比较时就容易糊涂。`is` 不能被重载这一点也值得反复强调,判断 `None` 时用 `is` 不只是风格问题,还能避免被 `__eq__` 干扰。 补充一点实际写代码时的习惯:哨兵对象可以用 `_MISSING = object()` 这种方式创建,然后判断 `if value is _MISSING`,比用 `None` 或某个特殊字符串更安全,也不会和正常值混淆。另外小整数缓存和字符串驻留确实只能当实现细节看,业务代码里比较值一律用 `==`,别为了“看起来快”去依赖 `is` 的结果。 整体上这篇适合给初学者当参考,示例也都比较直观。如果后续再展开,可以提一下 `!=` 和 `__ne__` 的关系,以及容器比较时身份和值比较混用容易踩的坑。
回复 支持 反对

使用道具 举报

发表于 7 小时前 | 显示全部楼层

Re: Python中is与==区别:整数缓存、None比较与哨兵对象

楼主的总结很到位,特别是把 == 的 NotImplemented 回退流程讲清楚了,这个细节很多人写代码时根本不知道。我来补几点平时踩坑的体会: 关于小整数缓存,-5 到 256 这个范围是 CPython 的实现细节,PyPy 或者某些嵌入式解释器可能不一样。所以像在 Python 3.8 里能在交互式环境看到 `a = 257; b = 257; a is b` 为 True,换到脚本文件里跑又变成 False,这种“时灵时不灵”的现象很容易把新人绕进去,结论就是别依赖它,值比较一律 ==。 哨兵对象这块可以再补一句实用写法:用一个单独的 `_sentinel = object()` 来当默认值,然后 `if value is _sentinel:` 判断,比用 None 当默认值更稳妥,因为 None 也可能是调用方合法传入的值。这个模式在写库函数默认参数时特别有用。 还有一个容易忽略的点:判断类型时也有人误用 `is`,比如 `type(x) is int`,虽然多数情况下能工作,但遇到子类或继承关系就要用 isinstance。is 只适合判断语义上的“同一个单例对象”,比如 None、True、False、Ellipsis、NotImplemented 这些。 最后提一下 NaN,`float('nan') == float('nan')` 是 False,因为它按
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

指导单位

江苏省公安厅

江苏省通信管理局

浙江省台州刑侦支队

DEFCON GROUP 86025

Hacking Group 021A

旗下站点

态势感知中心

应急响应中心

红盟安全

联系我们

官方QQ群:112851260

官方邮箱:security#ihonker.org(#改成@)

官方核心成员

关注微信公众号

Archiver|手机版|小黑屋| ( 沪ICP备2021026908号 )

GMT+8, 2026-11-24 10:43 , Processed in 0.027857 second(s), 18 queries , Gzip On, Redis On.

Powered by ihonker.com

Copyright © 2015-现在.

  • 返回顶部