Understanding Pythonβs Object Caching, Interning, and Memory Behavior
Python performs several smart memory optimizations behind the scenes. One of the most important is object caching (interning).
Understanding this helps you:
- avoid tricky
isbugs - write memory-aware code
- answer tricky interview questions confidently
π· What Is Object Caching in Python?
Python uses object caching (also called interning) as a performance optimization.
Instead of creating new objects every time, Python reuses certain immutable objects to:
- reduce memory usage
- improve execution speed
β οΈ Important: Caching is an implementation detail of CPython, not a strict language guarantee.
β Objects Python Does Cache
1οΈβ£ Small Integers
a = 10
b = 10
print(a is b) # True
π Cached range in CPython: -5 to 256
What happens:
- Same integer object reused
- Safe because integers are immutable
2οΈβ£ Boolean Values
a = True
b = True
print(a is b) # True
Facts:
- Only two boolean objects exist
-
TrueandFalseare singletons - Always cached
3οΈβ£ None
a = None
b = None
print(a is b) # True
None is a singleton β there is only one instance in the entire program.
β
Always safe to use is None.
4οΈβ£ Interned Strings (Conditional)
a = "hello"
b = "hello"
print(a is b) # Often True
Python may intern:
- short strings
- identifiers
- strings with letters, numbers, underscores
β οΈ Not guaranteed
a = "hello world"
b = "hello world"
print(a is b) # True or False (implementation-dependent)
β Objects Python Does Not Cache
1οΈβ£ Large Integers
a = 1000
b = 1000
print(a is b) # Usually False
π New object typically created.
2οΈβ£ Floating-Point Numbers
a = 10.5
b = 10.5
print(a is b) # False
Floats are immutable but not cached.
3οΈβ£ Complex Numbers
a = 10 + 5j
b = 10 + 5j
print(a is b) # False
Complex numbers are never cached.
4οΈβ£ Mutable Objects
a = []
b = []
print(a is b) # False
Includes:
listdictsetbytearray- class instances
Each mutable object gets separate memory.
5οΈβ£ Tuples (Special Case)
a = (1, 2)
b = (1, 2)
print(a is b) # Usually False
When tuples may be cached:
- empty tuple
()β - compile-time constants β οΈ
But do not rely on it.
π· Summary Table
| Object Type | Cached? |
|---|---|
| Small integers (-5 to 256) | β Yes |
| Large integers | β No |
| Boolean (True, False) | β Yes |
| None | β Yes |
| Short/identifier strings | β οΈ Sometimes |
| Float | β No |
| Complex | β No |
| Empty tuple | β Yes |
| List / Dict / Set | β No |
π· Why Python Uses Caching
Python caches objects to:
- reduce memory usage
- improve performance
- safely reuse immutable objects
Because immutables cannot change, sharing them is safe.
β Golden Rule
Use
==for value comparison.
Useisonly for identity checks (None,True,False).
π― Interview One-Liner
Python caches small immutable objects like small integers, booleans, and None for performance, but does not cache floats, complex numbers, or mutable objects.
Top comments (0)