Python __sizeof__ Method
Last modified November 18, 2026 Python 3.15
The __sizeof__ method returns the size of an object in bytes,
excluding the extra header the garbage collector adds. The recommended public
API is sys.getsizeof(), which calls the method and adds that
header. This article compares the two, shows how to count attributes and
container contents, discusses __slots__, recursive structures,
shared references and deep size measurement. Sizes vary between Python
versions and implementations, so the examples focus on relationships rather
than fixed byte counts.
__sizeof__ versus sys.getsizeof
sys.getsizeof() calls __sizeof__ and, for
garbage-collected objects, adds a header. It also handles edge cases such as
objects that do not define the method. The relationships below hold regardless
of the exact byte counts.
import sys
empty = []
big = list(range(100))
print("empty < big:", empty.__sizeof__() < big.__sizeof__())
print("gc header bytes:", sys.getsizeof(empty) - empty.__sizeof__())
print("longer string is larger:", "a".__sizeof__() < ("a" * 100).__sizeof__())
A list grows as elements are added, a longer string needs more storage, and
on this CPython build sys.getsizeof() adds 16 bytes of collector
header. Treat that number as implementation-specific.
$ python basic.py empty < big: True gc header bytes: 16 longer string is larger: True
Counting attributes in a custom class
The default object.__sizeof__ does not include an instance's
attributes. A custom implementation can add them using
sys.getsizeof().
import sys
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __sizeof__(self):
return (object.__sizeof__(self)
+ sys.getsizeof(self.x)
+ sys.getsizeof(self.y))
p = Point(3, 4)
print("counts attributes:", p.__sizeof__() > object.__sizeof__(p))
print("gc header added:", sys.getsizeof(p) - p.__sizeof__())
The custom value is larger than the bare object, and
sys.getsizeof() adds another collector header. The exact
difference depends on the interpreter but the relationship is stable.
$ python custom.py counts attributes: True gc header added: 32
Containers
A container should account for its own overhead, the internal storage and
each element. The internal list's __sizeof__ already includes its
pointer array, so only the elements are added separately.
import sys
class Bag:
def __init__(self, *items):
self.items = list(items)
def __sizeof__(self):
total = object.__sizeof__(self) + self.items.__sizeof__()
for item in self.items:
total += sys.getsizeof(item)
return total
small = Bag(1)
large = Bag(1, 2, 3, 4, 5)
print("more items cost more:", small.__sizeof__() < large.__sizeof__())
print("positive:", large.__sizeof__() > 0)
Adding elements increased the reported size. Using
sys.getsizeof(item) includes each element's own overhead rather
than just a pointer.
$ python container.py more items cost more: True positive: True
Classes with __slots__
A slots-based instance has no __dict__ and stores its fields in
a fixed layout. Its object.__sizeof__ already includes space for
the slots, so only the referenced values need adding.
import sys
class SlotPoint:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
def __sizeof__(self):
return object.__sizeof__(self) + sys.getsizeof(self.x) + sys.getsizeof(self.y)
class PlainPoint:
def __init__(self, x, y):
self.x = x
self.y = y
sp = SlotPoint(3, 4)
pp = PlainPoint(3, 4)
print("slot has no dict:", not hasattr(sp, "__dict__"))
print("plain has dict:", hasattr(pp, "__dict__"))
print("slot base larger:", object.__sizeof__(sp) > object.__sizeof__(pp))
The slots instance has no dynamic dictionary; its fixed layout is reflected
in a larger object.__sizeof__ value because the two field slots
are stored inline. Total memory can still be lower than for a dictionary-based
instance with many attributes.
$ python slots.py slot has no dict: True plain has dict: True slot base larger: True
Recursive structures
A tree node can include its children recursively. The method must handle missing children and, in real code, guard against cycles that would cause infinite recursion.
import sys
class TreeNode:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __sizeof__(self):
total = object.__sizeof__(self) + sys.getsizeof(self.value)
if self.left is not None:
total += self.left.__sizeof__()
if self.right is not None:
total += self.right.__sizeof__()
return total
leaf = TreeNode(1)
root = TreeNode(2, leaf, TreeNode(3))
print("root includes children:", root.__sizeof__() > leaf.__sizeof__())
The root's size includes both children and their values. A cycle — for example a node pointing back to its parent — would recurse forever without a visited set.
$ python tree.py root includes children: True
Shared references
Counting every reference separately double-counts shared objects. Tracking identifiers in a set gives each object weight once.
import sys
class Pair:
def __init__(self, first, second):
self.first = first
self.second = second
def __sizeof__(self):
total = object.__sizeof__(self)
seen = set()
for item in (self.first, self.second):
if id(item) not in seen:
seen.add(id(item))
total += sys.getsizeof(item)
return total
shared = [0] * 10
pair = Pair(shared, shared)
print("counted once:", pair.__sizeof__() < object.__sizeof__(pair) + 2 * sys.getsizeof(shared))
Both fields point at the same list, but it was measured only once. The same technique avoids double-counting in graphs with shared subobjects.
$ python shared.py counted once: True
Measuring deep size
sys.getsizeof() does not follow references on its own. For a
whole object graph, gc.get_referents() can walk the structure
while a visited set prevents loops and repeats.
import gc
import sys
def deep_size(obj, seen=None):
if seen is None:
seen = set()
if id(obj) in seen:
return 0
seen.add(id(obj))
size = sys.getsizeof(obj)
for referenced in gc.get_referents(obj):
size += deep_size(referenced, seen)
return size
data = {"a": [1, 2, 3], "b": [4, 5, 6]}
print("deep > shallow:", deep_size(data) > sys.getsizeof(data))
print("deterministic:", deep_size(data) == deep_size(data))
The deep measurement included the lists and integers inside the dictionary, and repeated calls returned the same value. Such helpers are useful for profiling, but they remain approximate because they cannot capture every implementation detail of memory allocation.
$ python deep.py deep > shallow: True deterministic: True
Best practices
A few rules keep __sizeof__ honest:
- Use
sys.getsizeof()as the public API; it adds the garbage collector header. - Add the sizes of attributes that the default
object.__sizeof__omits. - Account for container contents separately, since
sys.getsizeof()does not recurse. - Track visited identifiers to avoid double-counting shared objects and infinite recursion.
- Avoid hard-coding byte counts in tests — they vary across Python versions and builds.
Source
object.__sizeof__ - Python documentation
sys.getsizeof - Python documentation
gc.get_referents - Python documentation
__slots__ - Python documentation
In this article we have implemented the __sizeof__ method. We
have covered the collector header, custom classes, containers,
__slots__, recursive trees, shared references and deep size.
For related topics, see Python sys module,
Python garbage collection, and
Python __slots__.
Author
List all Python tutorials.