4 def get_size(obj
, seen
=None):
5 """Recursively finds size of objects in bytes"""
6 size
= sys
.getsizeof(obj
)
12 # Important mark as seen *before* entering recursion to gracefully handle
13 # self-referential objects
15 if hasattr(obj
, '__dict__'):
16 for cls
in obj
.__class
__.__mro
__:
17 if '__dict__' in cls
.__dict
__:
18 d
= cls
.__dict
__['__dict__']
19 if inspect
.isgetsetdescriptor(d
) or inspect
.ismemberdescriptor(d
):
20 size
+= get_size(obj
.__dict
__, seen
)
22 if isinstance(obj
, dict):
23 size
+= sum((get_size(v
, seen
) for v
in obj
.values()))
24 size
+= sum((get_size(k
, seen
) for k
in obj
.keys()))
25 elif hasattr(obj
, '__iter__') and not isinstance(obj
, (str, bytes
, bytearray
)):
26 size
+= sum((get_size(i
, seen
) for i
in obj
))
28 if hasattr(obj
, '__slots__'): # can have __slots__ with __dict__
29 size
+= sum(get_size(getattr(obj
, s
), seen
) for s
in obj
.__slots
__ if hasattr(obj
, s
))