Skip to content

Instantly share code, notes, and snippets.

@mgd020
Created September 3, 2020 23:50
Show Gist options
  • Save mgd020/1341be97499cd2fc645afb1fccb41e28 to your computer and use it in GitHub Desktop.
Save mgd020/1341be97499cd2fc645afb1fccb41e28 to your computer and use it in GitHub Desktop.
recursive getsizeof
import sys
def getsizeof_deep(o, verbose=False):
default_size = sys.getsizeof(0)
seen = set()
todo = [o]
size = 0
while todo:
o = todo.pop()
if id(o) in seen:
continue
seen.add(id(o))
s = sys.getsizeof(o, default_size)
size += s
if verbose:
print(s, type(o), repr(o), file=sys.stderr)
if isinstance(o, dict):
for key, value in o.items():
todo.append(key)
todo.append(value)
elif hasattr(o, '__iter__') and not isinstance(o, (str, bytes)):
todo.extend(o)
if hasattr(o, '__dict__'):
for key, value in o.__dict__.items():
todo.append(key)
todo.append(value)
if hasattr(o, '__slots__'):
todo.extend(getattr(o, slot) for slot in o.__slots__)
return size
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment