modified: diffout.py
[GalaxyCodeBases.git] / python / lib / pysize / pysize.py
blob7aa2ad39533577a2957c0b1be9e4ed9c6a09c013
1 import sys
2 import inspect
4 def get_size(obj, seen=None):
5 """Recursively finds size of objects in bytes"""
6 size = sys.getsizeof(obj)
7 if seen is None:
8 seen = set()
9 obj_id = id(obj)
10 if obj_id in seen:
11 return 0
12 # Important mark as seen *before* entering recursion to gracefully handle
13 # self-referential objects
14 seen.add(obj_id)
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)
21 break
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))
31 return size