Borislav Hadzhiev
Tue Jun 14 2022·2 min read
Photo by Jamakassi
Use the sys.getsizeof()
method to get the memory usage of an object, e.g.
sys.getsizeof(['a', 'b', 'c'])
. The method takes an object argument and
returns the size of the object in bytes. All built-in objects can be passed to
the sys.getsizeof()
method.
import sys print(sys.getsizeof({'name': 'Alice'})) # 👉️ 232 print(sys.getsizeof(100)) # 👉️ 28
The sys.getsizeof method returns the size of an object in bytes.
The object can be any type of object and all built-in objects return correct results.
The getsizeof
method only accounts for the direct memory consumption of the
object, not the memory consumption of objects it refers to.
Note that some Python objects like lists and dictionaries may reference other
objects and the getsizeof
method doesn't account for that.
There is a
recursive sizeof recipe in the
official docs. It uses getsizeof
recursively to find the size of an object and
the objects it references.
getsizeof()
method calls the __sizeof__
method of the object, so it doesn't handle custom objects that don't implement it.You can also import the getsizeof
method directly instead of importing the
entire sys
module.
from sys import getsizeof print(getsizeof([1, 2, 3])) # 👉️ 80 print(getsizeof(3.14 ** 10)) # 👉️ 24
The sys.getsizeof()
method takes an optional second argument - a default value
to return if the object doesn't provide means to retrieve the size.
If no default value is provided and the object's size cannot be calculated, a
TypeError
is raised.
Here are examples of passing different types of objects to the getsizeof
method.
from sys import getsizeof # 👇️ list print(getsizeof([])) # 👉️ 56 # 👇️ dict print(getsizeof({})) # 👉️ 64 # 👇️ int print(getsizeof(0)) # 👉️ 24 # 👇️ float print(getsizeof(0.0)) # 👉️ 24 # 👇️ string print(getsizeof('')) # 👉️ 49 # 👇️ set print(getsizeof(set())) # 👉️ 216 # 👇️ tuple print(getsizeof(())) # 👉️ 40 # 👇️ boolean print(getsizeof(True)) # 👉️ 28
Some objects like lists
reserve space for more objects than they contain.