Sub topic 7
Measuring object size: shallow versus deep
This chapter assumes you know that Python variables are names bound to objects, and that you can read basic class and container code. It also assumes you have met reference counting and the idea that several names can point to one object. By the end you will know what sys.getsizeof reports, what it leaves out, and how to measure the full footprint of a structure.
What sys.getsizeof reports
sys.getsizeof(obj) returns the size in bytes of the object's own memory block. 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 sizes of everything it refers to, counted recursively.
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 toThe list stores three pointers, so its shallow size is small (on a typical 64-bit CPython build, under 100 bytes). Each string is about 1,000 bytes or more. The list "contains" over 3,000 bytes of data, but getsizeof(items) does not show it.
What the number includes
The number from getsizeof covers these parts of one object:
- The object header: the reference count and the type pointer, 16 bytes on a 64-bit build.
- Fields specific to the type, such as the length of a list or the digits of an integer.
- For containers, the array of pointers they own. A list's pointer array is a separate allocation, but
getsizeofadds it to the list's size. - The extra header the cyclic garbage collector needs, for objects it tracks (lists, dicts, instances of user classes).
The number leaves out several things:
- Objects the container refers to.
- The allocator's own bookkeeping, and fragmentation inside pools and arenas.
- Memory held by C libraries behind an extension object. A NumPy array reports its buffer through its own
__sizeof__, but not every extension type does this accurately.
getsizeof calls the object's __sizeof__ method. A class can define __sizeof__ to report something different, so the number is only as good as that method.
Sizes of small built-in objects
Sizes depend on the Python version and platform. Run this on your own interpreter instead of trusting remembered numbers:
import sys
samples = [0, 1, 2**30, 2**60, 1.5, "", "a", "abc", b"abc", (), (1,), [], {}, set()]
for obj in samples:
print(f"{type(obj).__name__:6} {sys.getsizeof(obj):4} {obj!r}")Some patterns you will see:
- Integers grow with their magnitude. Python integers have arbitrary precision, stored as 30-bit digits, so
2**60takes more space than1. - An empty tuple, list, dict and set each have a different base size.
- A string's size is a fixed header plus one byte per character for ASCII text. Text with characters above U+00FF uses two or four bytes per character.
Container growth is not linear
A list over-allocates its pointer array so that append is cheap on average. The size reported by getsizeof therefore jumps in steps instead of growing with every element.
import sys
data = []
last = sys.getsizeof(data)
print(f"len=0 size={last}")
for n in range(1, 40):
data.append(n)
size = sys.getsizeof(data)
if size != last:
print(f"len={n:<2} size={size}")
last = sizeThe output shows a size change only at certain lengths. Between those lengths, the list has spare capacity that you have already paid for. The same applies to dicts and sets, which resize their hash tables in steps.
A list built by a comprehension or by list(iterable) can be smaller than one built by repeated append, because the first two can allocate closer to the final length. Do not rely on a specific ratio.
Why the shallow number misleads
Consider a list of one million small dicts. getsizeof on the outer list gives about 8 MB, the pointer array. Each dict is a separate block, with its keys and values behind it. The real footprint is many times larger. Using getsizeof on the outer container to judge memory use understates the cost, often by an order of magnitude.
The opposite error also occurs: adding up getsizeof for every item can overcount when items are shared. Python reuses some objects (small integers, interned strings) and programs often store the same object in many places. If a list holds 1,000 references to one 1 MB string, the data costs 1 MB, not 1 GB.
import sys
big = "x" * 1_000_000
shared = [big] * 1000 # 1000 references to one string
separate = ["x" * 1_000_000 for _ in range(3)]
print(sys.getsizeof(shared)) # small: 1000 pointers
print(len({id(s) for s in shared})) # 1 distinct object
print(len({id(s) for s in separate})) # 3 distinct objectsA correct deep measurement must count each distinct object once. That requires remembering which objects you have already visited.
Writing a deep size function
A recursive function can walk containers and track visited objects by id. The same set of visited ids also stops infinite recursion when a structure contains a cycle.
import sys
from types import FunctionType, ModuleType
def deep_getsizeof(obj, seen=None):
"""Approximate total size in bytes of obj and everything reachable from it."""
if seen is None:
seen = set()
if id(obj) in seen:
return 0
seen.add(id(obj))
# Do not walk into classes, functions, or modules: they are shared program state.
if isinstance(obj, (type, FunctionType, ModuleType)):
return 0
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)
else:
if hasattr(obj, "__dict__"):
size += deep_getsizeof(vars(obj), seen)
for cls in type(obj).__mro__:
for name in getattr(cls, "__slots__", ()):
if hasattr(obj, name):
size += deep_getsizeof(getattr(obj, name), seen)
return size
class Record:
def __init__(self, name, tags):
self.name = name
self.tags = tags
rec = Record("a" * 500, ["red", "green", "blue"])
print(sys.getsizeof(rec)) # the instance only
print(deep_getsizeof(rec)) # instance, its __dict__, the string, and the listThe function handles these cases:
- Shared objects are counted once, because the second visit returns 0.
- Cycles terminate, for the same reason.
- Instances are measured through their
__dict__and through__slots__, since a slotted class has no__dict__.
It does not handle everything. Objects that store data in C structures (NumPy arrays, database cursors) are measured only through __sizeof__. A string such as "red" that is interned elsewhere in the program is counted here even though your structure did not allocate it. Treat the result as an estimate of reachable memory, not an exact cost attributable to your structure.
Choosing a measurement tool
| Question | Tool | Notes |
|---|---|---|
| How big is this one object's own block? | `sys.getsizeof` | Shallow. Fast. |
| How much memory is reachable from this object? | A deep walker like the one above | Estimate. Shared objects are counted once. |
| Which lines of code allocated the memory? | `tracemalloc` | Counts allocations Python makes, with tracebacks. |
| How much memory does the process use? | OS tools, or the `resource` module | Includes the interpreter, allocator slack, and C libraries. |
These tools answer different questions, and their numbers will not agree. tracemalloc is covered in a later chapter. Process memory is almost always larger than the sum of object sizes, because the allocator keeps free blocks for reuse and does not always return them to the operating system.
Common mistakes
- Trusting
getsizeofon a container. It shows the pointer array, not the data. - Summing
getsizeofover items without deduplicating. This overcounts shared objects. - Comparing sizes across Python versions or platforms. Header sizes, string layouts, and dict layouts change between releases.
- Expecting exact sizes for floats and small ints in a list. Each element is a separate object plus an 8-byte pointer. A
listof one million floats uses far more memory than aarray.array("d")of the same values, which stores raw 8-byte numbers.
import sys
from array import array
values = [float(i) for i in range(100_000)]
packed = array("d", values)
list_total = sys.getsizeof(values) + sum(sys.getsizeof(v) for v in values)
print(list_total) # pointer array plus one float object each
print(sys.getsizeof(packed)) # one contiguous buffer of raw doublesThe array version is smaller because it stores no per-element object headers. The trade-off is that it holds only one numeric type and creates a new float object whenever you read an element.
Exercise
A list holds 1,000 references to the same 2 MB string. sys.getsizeof(lst) returns a small number. Your colleague says the list uses about 2 GB. Who is right about the memory used by the data, and what would your deep size function report?
Show answer
Neither number is right about the data. The list holds 1,000 pointers to a single string object, so the data costs about 2 MB plus the list's pointer array (roughly 8 KB). getsizeof(lst) reports only the pointer array. A deep size function that tracks visited ids reports about 2 MB plus the list block, because it counts the string once and returns 0 for the other 999 visits. Summing getsizeof over all items without deduplication would give the wrong figure of about 2 GB.
Exercise
You run deep_getsizeof(obj) and get 40 MB. After del obj, process memory drops by only 5 MB. Give two reasons the numbers can differ.
Show answer
First, the deep size includes objects shared with other parts of the program (interned strings, cached objects, data referenced elsewhere), and those stay alive after del obj. Second, the allocator may keep freed blocks, pools, or arenas for reuse instead of returning them to the operating system, so process memory falls less than the amount of memory freed.