Hello,
I am currently on the topic of slots. I am following this video tutorial:
I am using Python v3.12. The test code is:
import sys
from getsize import get_size
# from pympler import asizeof as get_size
def why_use_slots_example():
print('WHY USE SLOTS EXAMPLE')
class A:
def __init__(self):
self.x = 42
self.y = 42
self.z = 42
self.t = 42
self.u = 42
self.v = 42
self.w = 42
class B:
__slots__ = 'x', 'y', 'z', 't', 'u', 'v', 'w'
def __init__(self):
self.x = 42
self.y = 42
self.z = 42
self.t = 42
self.u = 42
self.v = 42
self.w = 42
print('Size of A (not slotted) instance:', sys.getsizeof(A()))
print('Size of B (slotted) instance: ', sys.getsizeof(B()))
# Use a recursive getsize function that counts the size of objects and their
# sub objects
print('\nRecursive size of A (not slotted) instance: ', get_size(A()))
print('Recursive size of B (slotted) instance: ', get_size(B()))
print('Memory savings factor = size A / size B = {:1.1f}'.format(get_size(A()) / get_size(B())))
I notice that in the video, the value for the recursive slotted B (get_size(B
)) result is greater than the non-recursive value. However, when I test it, the value is unchanged. The recursive function that I used is:
'''
Recursive function obtained from here:
https://gist.github.com/durden/0b93cfe4027761e17e69c48f9d5c4118
'''
import sys
def get_size(obj, seen = None):
"""Recursively finds size of objects"""
size = sys.getsizeof(obj)
if seen is None:
seen = set()
obj_id = id(obj) # Get memory address of object
if obj_id in seen:
return 0
# Important mark as seen *before* entering recursion to gracefully handle
# self-referential objects
seen.add(obj_id)
if isinstance(obj, dict):
size += sum([get_size(v, seen) for v in obj.values()])
size += sum([get_size(k, seen) for k in obj.keys()])
elif hasattr(obj, '__dict__'):
size += get_size(obj.__dict__, seen)
elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
size += sum([get_size(i, seen) for i in obj])
return size
My test results are:
Size of A (not slotted) instance: 48
Size of B (slotted) instance: 88
Recursive size of A (not slotted) instance: 658
Recursive size of B (slotted) instance: 88
Memory savings factor = size A / size B = 7.4
This part of the tutorial begins at the 3:46 minute mark. Is there something that I am doing wrong here? If so, can you please point it out.
Thank you.