Skip to content

Instantly share code, notes, and snippets.

@jiteshk23
Created April 30, 2020 07:10
Show Gist options
  • Save jiteshk23/bb88ed09591893fc63d41516dc4d11cb to your computer and use it in GitHub Desktop.
Save jiteshk23/bb88ed09591893fc63d41516dc4d11cb to your computer and use it in GitHub Desktop.
Python function to recursively calculate size of an object
import sys
def get_size(obj, seen=None):
"""Recursively finds size of objects"""
size = sys.getsizeof(obj)
if seen is None:
seen = set()
obj_id = id(obj)
if obj_id in seen:
return 0
# Important mark as seen *before* entering recursion to gracefully handle
# self-referential objects
seen.add(obj_id)
if isinstance(obj, dict):
size += sum([get_size(v, seen) for v in obj.values()])
size += sum([get_size(k, seen) for k in obj.keys()])
elif hasattr(obj, '__dict__'):
size += get_size(obj.__dict__, seen)
elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
size += sum([get_size(i, seen) for i in obj])
return size
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment