Sub topic 9
Interning and object caching
This chapter assumes you know that variables are names bound to objects, and that is compares identity while == compares value. Everything here describes CPython, and the exact behavior can change between versions.
Why CPython reuses objects
Creating an object costs time and memory. Some values are so common that CPython creates them once and hands out the same object every time. Two techniques do this:
- Caching keeps a fixed set of ready-made objects, such as small integers.
- Interning keeps one shared copy of each distinct string, so equal strings can be the same object.
Both are optimizations. Your code must never depend on them.
Small integer cache
CPython preallocates the integers from -5 to 256. Any operation that produces a value in that range returns the existing object.
a = int("256")
b = int("256")
print(a is b) # True: both names point to the cached object
c = int("257")
d = int("257")
print(c is d) # False: two separate objects
print(c == d) # True: same valueOther objects are also single shared instances: None, True, False, Ellipsis, and the empty tuple.
print(tuple() is ()) # True in CPythonString interning
CPython interns strings that look like identifiers (letters, digits, underscores) when it compiles them from source. Strings built at runtime are usually not interned, even when they are equal.
import sys
a = "".join(["py", "thon ", "memory"])
b = "".join(["py", "thon ", "memory"])
print(a == b) # True
print(a is b) # False: two separate objects
a = sys.intern(a)
b = sys.intern(b)
print(a is b) # True: both names now share one objectsys.intern returns the one canonical copy of a string. It is useful when a program holds a very large number of repeated strings, such as column names or tags from parsed data. The interned copy also speeds up dictionary lookups, because CPython can often compare identity before it compares content.
Common errors
The main mistake is using is to compare values. It can appear to work in tests and then fail on other inputs.
x = int("1000")
y = int("1000")
print(x is y) # False, although x == y is TrueA second source of confusion is that results change with context. Inside one module, two equal literals in the same code block may share one constant object. The same comparison can then give a different answer in the interactive interpreter, in a function, or on another Python version.
| Situation | Reliable check |
|---|---|
| Comparing numbers or strings | `==` |
| Checking for `None`, `True`, or `False` | `is` |
| Asking whether two names share one object | `is` |
Use is only for singletons such as None and when you really mean "the same object".
Practical guidance
- Do not intern strings by default. The intern table adds its own overhead, and it only pays off for many repeated strings.
- Do not rely on the small integer range. It is an implementation detail.
- Remember that caching affects reference counts. A cached object has many references and is never freed during normal execution.
Exercise
A test runs n = int("500") and m = int("500") and then asserts n is m. The assertion fails. Is this a bug in Python, and what should the test use instead?
Show answer
It is not a bug. 500 lies outside the cached range of -5 to 256, so each int("500") call creates a new object. The test should compare values with n == m.