IDRAS Python StudioStandalone Academy
Part 2: Variables, Assignment & PyObject Memory Model (Golden Chapter)
Reference Semantics, id(), type(), Mutability & Small Integer Interning
Why variables are name tags bound to heap objects, small integer caching (-5 to 256), reference counting, aliasing traps, and PyObject struct internals.
Intuition: Python mein variable ko ek "box" samajhna technically incomplete hai. Python mein jab aap x = 100 likhte hain, toh Python memory (Heap) ke andar ek naya PyObject banata hai jisme 100 store hota hai, aur x ko us object ka Reference (Pointer/Tag) bana deta hai.
Jab aap y = x likhte hain, toh koi naya data copy nahi hota; y bhi usi purane memory object ko point karne lagta hai. Is concept ko hum Aliasing / Reference Binding kehte hain!
Small Integer Caching: CPython performance ke liye -5 se lekar 256 tak ke numbers ko pehle se memory mein cache karke singleton bana kar rakhta hai. Isliye a = 256; b = 256; a is b hamesha True dega, par 257 ke liye interactive mode mein distinct heap objects create ho sakte hain.
Variables ko "tag" ya "label" ki tarah imagine karna intuition ke liye behtar hai, lekin university exams ya technical interviews mein CPython PyObject struct (ob_refcnt, ob_type) aur heap reference semantics explain karna anivarya hai.
In Python, variables are named references bound to objects allocated on the heap. Every Python object is represented at the C level by a PyObject structure comprising at minimum an ob_refcnt (reference count for deterministic deallocation) and an ob_type pointer (specifying the type descriptor and method table). Assignment performs pointer rebinding, not value copy.
- Equality (==): Tests equivalence of values by delegating to
__eq__()dunder protocol. - Identity (is): Tests whether both operands share the exact same memory address (i.e.
id(a) == id(b)). - Small Integer Interning: CPython maintains an array of pre-allocated integer singletons in
[-5, 256]range.
# Part 2: PyObject Reference Inspection & Interning
a = 256
b = 256
print("a is b (interned):", a is b) # True
x = 257
y = 257
print("x is y (heap):", x is y) # Distinct heap addresses in REPL
print("x == y (value):", x == y) # True