Back to results for “Memory Management”
Python › Memory Management & Garbage Collection

How does object interning (like small integer caching and string interning) affect memory and identity comparisons?

Advanced

Answer

CPython caches small integers (-5 to 256) and some string literals as singleton objects, so multiple variables referencing the same small int or interned string may share the same object in memory (verifiable with `is`). This is a memory optimization detail, not a guaranteed language feature -- relying on `is` for value equality of ints or strings outside interning ranges is a common bug source.
a = 100
b = 100
print(a is b)  # True -- small int caching

x = 1000
y = 1000
print(x is y)  # often False -- not cached, implementation-dependent
Real-world example A subtle bug arises when code checks `if user_id is 12345:` instead of `==`, working accidentally in testing due to caching but failing in production with larger, uncached integer values.

Common follow-ups: Why should you never rely on `is` for value equality?;How does sys.intern() force string interning manually?