Python · Memory & Internals

What is interning?

Hardinterningstringsintegersidentitymemory

Interview question

What is string/integer interning in Python?

How to answer

The short answer

Interning stores one canonical copy of certain immutable values and reuses that object for equal values. Identity (is) may then succeed even for separately spelled literals, but that is an optimization, not a language guarantee. Do not build business logic on it.

Strings

  • Some identifiers/literals may be automatically interned.
  • sys.intern(s) forces internment (useful for many repeated dict keys).

Integers

  • CPython caches a range of small integers (commonly -5..256). Those share identity.
  • Larger integers are not reliably cached.
Python
import sys

a = "pipeline"
b = "pipeline"
print(a is b)  # often True for literals (implementation detail)

x = sys.intern("user:" + "42")
y = sys.intern("user:42")
print(x is y)  # True

print(256 is 256)    # True (small int cache)
print((256 + 1) is (257))  # may be False for computed values
print(257 == 257)    # always compare with ==

Interview rule: Explain interning as a memory/speed optimization; always compare values with == unless checking singletons like None.

Lock it in with a real drill

You remember an answer longer once you have used it. Try a hands-on problem on this concept.

Open related drill