Lesson · Python Internals
Memory Model & Object Layout
80 min readMemory Model & Object Layout
Python variables hold references to heap objects rather than raw inline values in the general model. CPython object headers, reference counts, and allocation overhead matter when millions of small objects are involved.
Learning goals
- Explain why Python names are references to heap objects and what a reference count tracks.
- Use
sys.getsizeofand say precisely what it includes and what it leaves out. - Predict the effect of assignment and argument passing using the reference model, including in-place mutation through an alias.
- Distinguish mutable from immutable objects by what operations do to the existing object.
- Sort observations into language guarantees versus CPython details, with size numbers in the second group.
Mental model
The diagram is why two names can see one object and why removing a name does not immediately free memory: the reference count drops, and only at zero does CPython deallocate the object. It also explains sys.getsizeof: the number covers the object in the diagram, header plus payload, and for a container the payload is the array of references, not the objects they point at.
Mental model
read it top to bottom
name → reference → heap object [header | payload]
header: type pointer and reference count
payload: a value or references to other objectsCore idea
Python's memory model is a graph: names, container slots, and attributes are references, and the objects they reach live on the heap with a header that tracks type and reference count. Most operations move references rather than copy values, so one object can be seen through many paths and stays alive while any path reaches it. The reference-based model is the language-level part; exact header sizes and getsizeof numbers are CPython specifics.
Objects on the heap
CPython stores every Python value in a heap object: a block carrying a header (type pointer and reference count) plus the object's payload. Names and containers do not hold values; they hold references to those objects, and the header is what makes type() and lifetime management possible. sys.getsizeof reports the size of one such object in bytes, header included and referenced objects excluded.
References
A Python-level reference is a connection from a name, container slot, attribute, frame, or other object to another object. Object lifetime depends on the complete reference graph.
Small-object overhead
Each Python object can carry metadata such as type and reference-count information in addition to its payload. For millions of tiny values, this overhead can dominate memory use.
Mutable vs immutable behavior
Mutable objects such as lists, dicts, and sets can change in place, so two references to one object both observe the change; immutable objects such as ints, strings, and tuples cannot change after creation, and operations on them build new objects. The distinction decides what assignment and function calls share: passing a list shares it and its future mutations, while rebinding a name to a different object never changes the object other names still reference.
Language guarantees vs CPython details
The language guarantees observable behavior that every implementation must preserve: reference semantics, mutability rules, and dictionary insertion order are examples. CPython-specific details include object header layouts, exact sys.getsizeof values, and the reference-counting strategy for reclaiming unreachable objects; those can change between versions and platforms, so use them for diagnosis rather than as contracts.
Walkthrough
small_int = 42binds a name to anintobject living on the heap;sys.getsizeof(small_int)reports that object's own bytes, header included, and the name itself adds no payload anywhere.empty_list = []creates a list object; itsgetsizeofresult counts the header plus the initial array of reference slots, which is why even an empty list is tens of bytes rather than zero.three_items = [1, 2, 3]reports a larger number because the slot array grew to hold three references; the integers themselves are separate objects and are not included in the list's size.- Predict before running: which of the three numbers is largest, and why summing
getsizeofoverthree_itemscan never report the total memory its element objects use.
Experiments to try
- Print
getsizeoffor0,2**1000,"abc", and"a" * 10_000; note which sizes grow with content and which stay small. - Bind two names to one list (
a = [1, 2]; b = a), append throughb, and check both names plusid(a) == id(b); explain the result with the reference model. - Delete one of two names bound to a big object and confirm the object is still reachable through the other; explain with reference counting why it was not freed yet.
- Compare
sys.getsizeof(tuple(range(10)))withsys.getsizeof(list(range(10)))and explain the difference with what each object stores.
Common mistakes
- Reading
sys.getsizeofas the total memory of an object tree: it counts one object, so a list's number excludes every element it references. - Expecting assignment to copy:
b = abinds another reference, so mutating throughbis visible throughabecause both names reach the same object. - Assuming sizes are language guarantees: header layouts and
getsizeofvalues vary by CPython version, platform, and build, so comparisons across machines need the same environment. - Forgetting the per-object header when estimating memory for millions of small values: each object pays a type pointer and a reference count on top of its payload, which can dwarf the raw data estimate.
Practice: Easy
- Run the worked example and print
type,id, andgetsizeoffor each value; label which line describes the name, which the reference, and which the object. - Bind
b = three_items, append4throughb, and printthree_items; explain the result in one sentence using the reference model. - Compare
getsizeof([1, 2, 3])andgetsizeof([1, 2, 3, 4]); state how many bytes one more slot costs on your platform.
Practice: Medium
- Estimate the memory of a list of 10,000 large integers: measure
getsizeof(values)and addsum(getsizeof(v) for v in values); compare with10_000 * 8bytes and name every component the total includes. - Write a function that appends to a list argument, call it with a list passed under two names, and show the caller's list changed; explain with the reference model why the callee never received a copy.
- Show a tuple and a list holding the same three integers: compare
getsizeoffor both and separate the layout difference from the implementation-detail part.
Practice: Hard
- Build a small memory report for a structure of your choice (a list of dicts with string keys): measure the container, the keys, the values, and the total; propose one change that reduces object count and estimate the savings before testing.
- Use
sys.getrefcount(object)while binding and deleting names; explain each count from the reference graph, including the extra count the call itself adds. - Explain, using the array of references, why a list of a million identical objects stores a million references (8 bytes each) but not a million copies of the objects, and compute both numbers for a concrete example; connect the result to what
delon the list frees.
Lesson checklist
- I can describe the layout of a CPython object as header plus payload and say what the header tracks.
- I can explain why assignment and argument passing move references rather than copy values.
- I can read
sys.getsizeofcorrectly and state what it excludes. - I can separate a language guarantee from a CPython measurement in my own descriptions.
Remember
Python's data model is a graph of references over heap objects, each object carrying its own header with type and reference count. Assignment, argument passing, and container storage move references, so sharing and in-place mutation are the norm; object layout numbers such as `sys.getsizeof` results are CPython details useful for diagnosis, while reference semantics and mutability rules are the language guarantees. When memory matters at the scale of millions of small objects, count the per-object header, not just the payload.
Interview angles
What is the main purpose of **Objects on the heap**?+
Every Python value lives in a heap object carrying a header (type pointer and reference count) plus its payload. Names and containers hold references to those objects, and sys.getsizeof reports the size of one object, header included and referenced objects excluded.
What should you pay attention to when using **References**?+
A Python-level reference is a connection from a name, container slot, attribute, frame, or other object to another object. Object lifetime depends on the complete reference graph.
How does **Small-object overhead** fit into this lesson?+
Each Python object can carry metadata such as type and reference-count information in addition to its payload. For millions of tiny values, this overhead can dominate memory use.
Why does `b = a` not protect `a` from later mutations made through `b`?+
The assignment copies the reference, not the object, so both names reach the same list or dict, and an in-place change through either name is visible through the other. If you need independence, copy explicitly (a.copy() or copy.deepcopy) and be aware of which copy semantics you chose.