Get the size of an object.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import types | |
import gc | |
ignored_types = ( | |
type, | |
types.FunctionType, | |
types.LambdaType, | |
types.MethodType, | |
types.BuiltinFunctionType, | |
types.BuiltinMethodType, | |
types.ModuleType, | |
) | |
def get_size(obj, seen=set()): | |
if isinstance(obj, (int, float, complex, str, bytes, bytearray)): | |
return sys.getsizeof(obj) | |
elif isinstance(obj, ignored_types) or id(obj) in seen: | |
return 0 | |
else: | |
seen.add(id(obj)) | |
size = sys.getsizeof(obj) | |
for child in gc.get_referents(obj): | |
size += get_size(child, seen) | |
return size |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment