Sub topic 7
Measuring object size: shallow versus deep
This chapter assumes you know Python lists, dicts, and classes. It also assumes you can run a script and know that names refer to objects. It covers what sys.getsizeof reports, why that number is often misleading, and how to estimate the full size of a structure.
What sys.getsizeof reports
sys.getsizeof(obj) returns the size in bytes of the object's own memory. It does not follow references to other objects. This is called a shallow size. A deep size is the object's own size plus the size of everything it refers to, directly or indirectly.
A list stores only references (pointers) to its items. The list's size grows by one pointer per item, whatever the items are.
import sys
items = ["x" * 1000, "y" * 1000, "z" * 1000]
print(sys.getsizeof(items)) # the list object only
print(sum(sys.getsizeof(s) for s in items)) # the strings it refers toOn a typical 64-bit CPython build, the first number is under 100 bytes. The second is over 3,000. The list looks tiny because its three strings are separate objects.
What the number includes
The result covers the object header, the reference count, the type pointer, and the object's own data. For a container this is its internal array of references. If the object is tracked by the cyclic garbage collector, getsizeof also adds the collector's bookkeeping header.
Some results surprise people:
- An empty list and a list with elements differ by the space for the references only.
- Lists over-allocate, so the size jumps in steps as you append.
- Instances of ordinary classes report a small size because their attributes live in a separate
__dict__. - Small integers and interned strings are shared, so counting them once per reference overstates memory use.
Computing a deep size
To estimate a deep size, walk the references and add each object's shallow size. You must remember which objects you have already counted. Shared objects would otherwise be counted twice, and cyclic references would cause infinite recursion.
import sys
def deep_getsizeof(obj, seen=None):
if seen is None:
seen = set()
obj_id = id(obj)
if obj_id in seen:
return 0
seen.add(obj_id)
size = sys.getsizeof(obj)
if isinstance(obj, dict):
for key, value in obj.items():
size += deep_getsizeof(key, seen)
size += deep_getsizeof(value, seen)
elif isinstance(obj, (list, tuple, set, frozenset)):
for item in obj:
size += deep_getsizeof(item, seen)
elif hasattr(obj, "__dict__"):
size += deep_getsizeof(vars(obj), seen)
return size
shared = "y" * 1000
data = ["x" * 1000, shared, shared]
print(sys.getsizeof(data))
print(deep_getsizeof(data))The seen set holds object identities. The string shared appears twice in the list but is counted once, which matches the real memory use.
Limits of this approach
The function above is an estimate, not an exact accounting.
- It ignores
__slots__attributes, because instances with slots have no__dict__. - It does not know about types implemented in C extensions, such as NumPy arrays, which manage their own buffers.
- It counts objects that other parts of the program also reference, such as module-level constants and cached objects.
- It does not include allocator overhead. CPython's allocator rounds requests up and adds padding, so the operating system sees more memory than the sum of the sizes.
Choosing a measurement
| Question | Tool |
|---|---|
| How big is this one object? | `sys.getsizeof` |
| How big is this whole structure? | A deep walk like `deep_getsizeof` |
| Which lines allocate the most? | `tracemalloc` |
| How much memory does the process use? | An operating system tool, such as `ps` |
Exercise
A list holds 1,000 references to the same 10,000-byte bytes object. What does sys.getsizeof return for the list, and what does deep_getsizeof return, approximately?
Show answer
sys.getsizeof returns only the list's own size: about 8,000 bytes for the references plus a small header and any over-allocation. deep_getsizeof returns that plus about 10,000 bytes for the bytes object, counted once, because the seen set skips the 999 repeated references. The total is roughly 18,000 bytes, not 10 million.