Interning
Interning reuses one object for equal values so identity matches equality. CPython interns small integers and some strings; sys.intern does it on demand.
Detailed Explanation
Creating a new int or str for every occurrence would waste memory. CPython keeps a cache of small integers, historically -5 through 256, and returns the same object each time you write those literals. Many identifiers and short strings that look like names are interned at compile time. That is why a is b sometimes works for numbers and strings in a demo and fails when the value arrives from JSON or from str(n).
sys.intern(s) stores s in a table and returns the interned object. Later sys.intern of an equal string returns the same object. Dicts already hash strings; interning helps when you compare many strings with is on purpose, such as interned identifiers in a parser. It is not a general speedup for application strings.
You should not depend on interning for correctness. == is the equality test. is is the identity test. Interning is an optimisation that makes those tests coincide for some values. A code change, a Python upgrade, or a different implementation (PyPy) can intern a different set.
The integer cache is a CPython detail. The language does not promise that 256 is 256. The compiler may also merge equal constants in one code object, so a .py file can show 257 is 257 as true while the REPL, which compiles each line separately, shows false.
None, True, False are singletons by language rule, not by a cache you should analogise to ints. is None is correct. is 0 is not.
Code Examples
import sys
print(256 is 256) # True in CPython (small-int cache)
a = 257
b = 257
print(a == b) # True, always use this
s1 = sys.intern("order-status")
s2 = sys.intern("order-status")
print(s1 is s2) # True# Values from the outside are not interned just because they look familiar.
raw = "".join(["ad", "a"]) # built at runtime, not a literal
print(raw == "ada") # True
print(raw is "ada") # False in generalCommon Gotchas
`is` for numbers or strings
a passing unit test on literals, a production bug on parsed data.
Interning large arbitrary strings
the table lives for the process. Intern identifiers, not request bodies.
Other implementations differ
write to the language spec, not to CPython's cache sizes.
`True is True` is a singleton guarantee
that does not extend to `1 is True` (which is false) even though `1 == True`.