← 中文资源

简体中文版本

intern 让等值字符串共享规范对象

sys.intern 为每个字符串值返回规范对象:运行期拼出的等值字符串从此共享身份,重复字段名场景下省内存、加速比较。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

equal contents: True same object: False
after intern, same object: True
distinct contents: 3 distinct objects: 3

实现说明

各个操作都建立在顶层绑定之上:suffixes、raw、canonical。

使用要点

  • 每一步打印都带着自己的标签:equal contents:、after intern, same object:、distinct contents:。

常见问题

包管理器会看到什么?

一份空的依赖清单。示例没有需要抓取的导入。 跨调用保留的状态放在这些顶层绑定里:suffixes、raw、canonical。

代码示例

import sys

suffixes = ("read", "write", "read", "admin")

# Runtime concatenation: equal contents, distinct string objects
raw = ["perm:" + s for s in suffixes]
print("equal contents:", raw[0] == raw[2], "same object:", raw[0] is raw[2])

# intern returns the canonical object for each value; equal strings share identity
canonical = [sys.intern(t) for t in raw]
print("after intern, same object:", canonical[0] is canonical[2])

# For workloads full of repeated names (parsers, caches, protocol fields) the
# canonical form means fewer live objects and faster identity-based comparisons
print("distinct contents:", len(set(canonical)), "distinct objects:", len({id(t) for t in canonical}))