IDRASAcademic OS
Curriculum

IDRAS Python StudioStandalone Academy

Syllabus Navigation30 Parts
PART 2 OF 29Estimated Reading: 25 mins

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.

Micro-Concepts Covered:
PyObject C-Structure (ob_refcnt, ob_type)Variable Binding vs Physical BoxesSmall Integer Interning Cache (-5 to 256)Identity (is) vs Equality (==)Mutable vs Immutable Objects & Aliasing Traps
Hinglish Samjho — Intuitive Mental Model

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.

UNDERSTANDING ONLY — NOT AN EXAM ANSWER

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.

Academic Formal Definition & Exam-Ready AnswerCPython 3.12 Spec
1. Formal Technical Definition:

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.

2. Exam-Ready Structured Comparison: Identity vs Equality:
  • 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.
Runnable Verified Code Example
# 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
Authoritative References & Official Documentation:
Part 2 of 30