Sub topic 9
Interning and object caching
This chapter covers why two names sometimes refer to the same object even though you never assigned one to the other. It assumes you know the material from earlier chapters: names bound to objects, is versus ==, and reference counts. Everything here describes CPython. The details are implementation choices, not language guarantees, and they change between versions.
Why CPython reuses objects
Creating an object costs time and memory. Some values appear so often that CPython creates them once and hands out references to the same object. Two techniques do this:
- Caching keeps ready-made objects for common values, such as small integers.
- Interning keeps a table of unique strings, so equal strings can share one object.
Both rely on immutability. If a value cannot change, sharing one object between many names is safe. A shared mutable list would be a bug, as the aliasing chapter showed.
The small integer cache
CPython preallocates the integers from -5 to 256 at startup. Any operation that produces one of these values returns the existing object.
a = int("256")
b = int("256")
print(a is b) # True: both names refer to the cached object
c = int("257")
d = int("257")
print(c is d) # False: each call built a new int
print(c == d) # True: the values are equalThe example uses int("...") on purpose. If you write x = 257 and y = 257 on one line or in one function, the compiler often stores a single constant in the code object, and x is y can be True. That result comes from compile-time constant sharing, not from the small integer cache. The same code can behave differently at the interactive prompt, in a script, or in a function.
Other singletons and cached objects
Several other values are shared in CPython:
None,True,False, andEllipsiseach have exactly one instance. This is whyx is Noneis the correct test.- The empty tuple is a single object.
- Strings of length 0 or 1 in the Latin-1 range are cached.
print(tuple() is ()) # True in CPython: one empty tuple
print(float("1.5") is float("1.5")) # False: floats are not cached
print(().__class__ is tuple) # TrueFloats, lists, dicts, and other containers are not cached as values. For some of them CPython keeps free lists. A free list holds recently freed objects, so the next allocation of that type can reuse the memory. The reused memory holds a new object with a new identity, so a free list is a speed optimization, not a sharing mechanism.
String interning
Interning means storing one canonical copy of a string in a table. When code asks for an equal string, it receives the canonical object.
CPython interns some strings automatically:
- Names the compiler sees as identifiers: variable names, attribute names, function names, and keyword argument names.
- String literals in source code that look like identifiers (letters, digits, underscore).
- The keys of instance and module dictionaries, because those keys are attribute names.
Strings built at runtime are generally not interned.
import sys
s1 = "".join(["hel", "lo world"])
s2 = "".join(["hel", "lo world"])
print(s1 == s2) # True: same characters
print(s1 is s2) # False: two separate objects
i1 = sys.intern(s1)
i2 = sys.intern(s2)
print(i1 is i2) # True: both names now refer to the canonical copysys.intern takes a string and returns the interned version. If an equal string is already in the table, you get that one back. If not, the string you passed is added and returned. Rebind your names to the return value. Interning s2 does not change s2 itself, so keep using i2.
Why interning is faster
Interned strings let CPython compare by pointer instead of by content. When a dictionary looks up a key, it first checks whether the stored key and the search key are the same object. If they are, it skips the character comparison. Attribute lookup relies on this, because attribute names are interned.
For your own code, the benefit appears in a narrow case: many lookups or comparisons against a small set of repeated strings that were created dynamically, such as tokens parsed from a file.
Interning to save memory
Interning also removes duplicates. If a program reads a million records and each one has a status string like "pending" created by parsing, you hold a million separate string objects. Interning collapses them to one.
import sys
statuses = ["".join(["pen", "ding"]) for _ in range(5)]
print(len({id(s) for s in statuses})) # 5: five distinct objects
shared = [sys.intern(s) for s in statuses]
print(len({id(s) for s in shared})) # 1: one canonical objectAfter the loop, statuses still holds its five originals. The memory is only released once you drop that list and keep only shared.
Never use `is` to compare values
Because sharing depends on version, compiler decisions, and how a value was built, identity checks on numbers and strings give unreliable answers.
# Wrong: works for small values, fails for others
def is_ten(n):
return n is 10
# Right
def is_ten(n):
return n == 10Python 3.8 and later emit a SyntaxWarning for is with a literal, because this mistake is common. Use is only for singletons (None, True, False) and when you really mean "the same object".
Immortal objects in newer versions
Since Python 3.12, some objects are immortal: their reference count is fixed at a special value and never changes, so they are never freed. The small integers, None, True, False, and many interned strings are immortal. This removes reference-count updates for the most-shared objects. It also matters when you inspect counts:
import sys
print(sys.getrefcount(None) > 1000) # True on 3.12+: a huge fixed valueOn older versions, sys.getrefcount(None) returns a real count that rises and falls. Do not write code that depends on either result. You will mainly notice the difference when a chapter-style experiment with getrefcount gives an odd number for a small integer or a common string.
Edge cases and limits
- Interned strings can live a long time. Depending on the version, strings placed in the intern table may stay alive until the process exits. Do not intern unbounded, unique data such as request IDs or user-supplied text. You would grow the table without ever reclaiming it.
sys.internaccepts only exactstrobjects. Passing a subclass ofstrraisesTypeError.- Equal values are not always the same object, and the reverse can also surprise you. Two names may share one object after constant folding, even when you never assigned one to the other. Immutable objects make this harmless. Mutable objects are never shared this way.
- Tuples of constants can be folded into a single constant at compile time, so
(1, 2) is (1, 2)may beTrueinside one function. Tuples built from runtime values are separate objects.
Choosing a technique
| Situation | Approach |
|---|---|
| Comparing numbers or strings for equality | Use `==` |
| Checking for `None` | Use `is None` |
| Many duplicate strings created at runtime, in a bounded set | Use `sys.intern` |
| Many duplicates of arbitrary immutable values | Keep your own dictionary that maps each value to one canonical object |
| Unbounded unique strings | Do not intern |
A dictionary-based canonicalizer works for any hashable immutable type and gives you control over its lifetime, because you can clear it:
def make_canonicalizer():
table = {}
def canonical(value):
return table.setdefault(value, value)
return canonical
canon = make_canonicalizer()
a = canon("".join(["ab", "cd"]))
b = canon("".join(["ab", "cd"]))
print(a is b) # True: the second call returned the first objectBecause table is local to the closure, the whole table is freed once you drop canon. That makes this approach safer than a global intern table when the data is scoped to one job, such as parsing one file.
Exercise
A colleague writes if response_code is 200: and it passes every test. Another colleague says it will eventually fail. Who is right, and what should the line be?
Show answer
The second colleague is right. 200 lies inside the small integer cache (-5 to 256), so equal values from most operations are the same object and the test passes. A code like 1000 would not be cached, and a value produced at runtime may not be the shared object on every version or code path. The line should be if response_code == 200:, which compares values and works for any int.
Exercise
You parse a log file with two million lines. Each line yields a level string such as "ERROR" or "WARNING", built by slicing the line. Memory use is high. What change reduces it, and what limit should you keep in mind?
Show answer
Pass each level string through sys.intern (or a local dictionary canonicalizer) and keep only the returned object. The two million slices collapse into a handful of shared objects, and equal-level comparisons can use the pointer shortcut. The limit is that this only suits a small, bounded set of repeated values. Interning unique strings such as line IDs would grow the intern table without bound, and in some versions those strings stay alive until the process exits.