Skip to content

Instantly share code, notes, and snippets.

@aeros
Last active November 14, 2019 08:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aeros/632bd035b6f95e89cdf4bb29df970a2a to your computer and use it in GitHub Desktop.
Save aeros/632bd035b6f95e89cdf4bb29df970a2a to your computer and use it in GitHub Desktop.
Get the size of an object.
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