Created
March 27, 2020 20:01
-
-
Save carlomazzaferro/ef1c6629633efe4db86e1f5365c89fa7 to your computer and use it in GitHub Desktop.
Get object size
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 | |
from types import ModuleType, FunctionType | |
from gc import get_referents | |
# Custom objects know their class. | |
# Function objects seem to know way too much, including modules. | |
# Exclude modules as well. | |
BLACKLIST = type, ModuleType, FunctionType | |
def getsize(obj): | |
"""sum size of object & members.""" | |
if isinstance(obj, BLACKLIST): | |
raise TypeError('getsize() does not take argument of type: '+ str(type(obj))) | |
seen_ids = set() | |
size = 0 | |
objects = [obj] | |
while objects: | |
need_referents = [] | |
for obj in objects: | |
if not isinstance(obj, BLACKLIST) and id(obj) not in seen_ids: | |
seen_ids.add(id(obj)) | |
size += sys.getsizeof(obj) | |
need_referents.append(obj) | |
objects = get_referents(*need_referents) | |
return size |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment