When Python Shares Strings: Interning Explained
This article explains when two equal Python strings are the same object, how CPython interns names and literals, how sys.intern reduces the memory of repeated runtime strings, and why identity must never replace equality.
Two equal strings may be one object or two, and the difference is visible only through the operator is, which compares identities rather than values. CPython keeps a table of interned strings, from which equal strings can share a single object, and it fills that table automatically with the names that appear in programs. The present article examines when two equal strings are the same object, why the answer depends on how and when each string was created, how sys.intern saves memory for repeated strings built at runtime, and why identity must never replace equality in ordinary code. A single shared object for each repeated name is the secret weapon behind the speed of attribute lookups in Python.
Equal Values, Shared Objects
String literals are created by the compiler, not at runtime: every literal of a function or module becomes a constant of its code object, and equal literals compiled together share one constant. Literals compiled separately, as in successive lines of an interactive session, may or may not share an object; identifier-like literals do, because the compiler interns them.
def evaluate(source, name):
return eval(compile(source, name, "eval"))
a = "Hello there my friend!"
b = "Hello there my friend!"
print(a == b, a is b) # Output: True True
first = evaluate('"Hello there my friend!"', "<line 1>")
second = evaluate('"Hello there my friend!"', "<line 2>")
print(first == second, first is second) # Output: True False
one = evaluate('"hello_world"', "<line 1>")
two = evaluate('"hello_world"', "<line 2>")
print(one is two) # Output: True
The first pair is identical because both literals belong to the same compiled module and the compiler stores the constant once, a mechanism visible in the constants examined in the article devoted to bytecode. The second pair is compiled separately, and since the string contains spaces it is not interned, so two objects result. The third pair looks like an identifier, made only of letters, digits and underscores, so CPython interns it and both compilations return the same object. These rules are implementation details of CPython; the language reference states only that equal literals may or may not be the same object, and that this behaviour may change.
The Clone Problem: Equal Strings, Different Objects
Strings built while the program runs, by concatenation, join, formatting, decoding or reading a file, are new objects, even when an equal string already exists. The function sys.intern returns the canonical copy of a string from the interned table, adding it if necessary.
import sys
literal = "hello_world"
built = "".join(["hello", "_world"])
print(built == literal, built is literal) # Output: True False
print(sys.intern(built) is literal) # Output: True
city = "New York City"
print(sys.intern("New York City") is city) # Output: True
The string assembled by join has the same value as the literal but is a separate object. After sys.intern, it is replaced by the canonical object, which here is the identifier-like literal that the compiler had already interned. The last line shows that a literal and sys.intern of an equal literal are also the same object, because sys.intern adds the literal constant itself to the table and returns it.
Saving Memory with sys.intern
Interning pays off when a program creates many equal strings at runtime, as when it parses a log or a CSV file whose columns repeat a few values. The following example builds 200,000 such strings and measures the memory they occupy with and without interning.
import sys
import tracemalloc
words = ("alpha beta gamma delta " * 50_000).split()
tracemalloc.start()
plain = [word + "_city" for word in words]
plain_memory = tracemalloc.get_traced_memory()[0]
tracemalloc.stop()
del plain
tracemalloc.start()
interned = [sys.intern(word + "_city") for word in words]
interned_memory = tracemalloc.get_traced_memory()[0]
tracemalloc.stop()
print(len(interned), len(set(map(id, interned)))) # Output: 200000 4
print(plain_memory > 5 * interned_memory) # Output: True
On the test machine, with CPython 3.12, the plain list kept about 11.8 megabytes alive, one string object for each element, whereas the interned list needed about 1.6 megabytes, essentially the list itself, because its 200,000 elements refer to only four string objects. Each temporary string is still created before sys.intern replaces it, so interning saves the memory that is retained, not the work of building the strings. Interning is therefore a form of caching keyed by value, close in spirit to the memoization described in the article devoted to lru_cache.
The speed benefit is narrower than often claimed. The operator == already returns immediately when both operands are the same object, and comparing two distinct equal strings is a fast comparison of their memory. The documented gain is in dictionary lookups: a lookup compares identities before values, so interned keys, such as the attribute names of modules, classes and instances, which CPython interns automatically, are found without comparing their characters, as explained in the article devoted to dictionary internals.
Pitfalls of String Interning
Interning is an optimization of the implementation, and most of its pitfalls come from treating it as a property of the language. Five pitfalls are distinguished, which are the following:
- Identity instead of equality. Code that compares strings with
isworks only for strings that happen to be shared; since Python 3.8 the compiler warns whenisis used with a literal. - Implementation-dependent results. Which literals are shared depends on how the code is compiled and on the interpreter version, so the same test may give different results in a script and in an interactive session.
- Only exact strings.
sys.internrejects subclasses ofstr. - References are required. The documentation warns that interned strings are not immortal; the benefit lasts only while the program keeps a reference to the value that
sys.internreturned. - Interning everything. Strings that rarely repeat gain nothing from interning and add an entry to a global table.
The first and third pitfalls are reproduced in the following example.
import sys
import warnings
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
compile('status is "ok"', "<check>", "eval")
print(caught[0].category.__name__) # Output: SyntaxWarning
print(caught[0].message)
# Output (CPython 3.12): "is" with 'str' literal. Did you mean "=="?
class Label(str):
pass
try:
sys.intern(Label("ok"))
except TypeError as error:
print(error) # Output: can't intern Label
The warning appears when the code is compiled, before it runs, which makes the mistake visible as soon as the module is imported. The subclass is rejected because a subclass may carry extra state or behaviour that a shared canonical object could not represent.
Choosing Between Identity and Equality
Consequently, interning is a tool for memory and lookup speed in specific workloads, and identity comparisons remain reserved for singletons, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Comparing two strings | ==, always |
Comparing with None, True, False or a sentinel object |
is |
| Millions of repeated strings created at runtime, kept in memory | sys.intern on each value as it is read |
| Dictionary keys or attribute names | Nothing; CPython interns names automatically |
| Short-lived or rarely repeated strings | No interning |
| Checking which strings are interned, for diagnosis | sys._is_interned (CPython 3.13 and later, implementation-specific) |
Conclusion
It is concluded that string interning lets equal strings share a single object, that CPython applies it automatically to the names and identifier-like literals of programs, and that sys.intern extends it to strings built at runtime, which can reduce the memory of highly repetitive data by an order of magnitude. This magic is an implementation detail rather than a language guarantee, so it must never justify comparing strings with is. Interning is a particular case of a general design idea, sharing one immutable object among many users, which the Flyweight pattern formalizes and which is developed in a future article of this series.