intern Canonicalizes Equal String Objects

sys.intern returns the canonical object for each string value, so equal strings built at runtime share identity, trimming memory and speeding comparisons.

PythonData Integrity

Code

pythonsnippet
15 lines
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}))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

How the snippet works

The file’s state is a handful of top-level bindings: suffixes, raw, canonical.

What to watch for

  • Self-contained — no imports beyond what the runtime already provides.

Using it

Running the file prints labeled results such as equal contents:, after intern, same object:, distinct contents: — each operation’s effect is visible in the output.

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `suffixes`, `raw`, `canonical`.