__sizeof__ Not Getting Called By Sys.getsizeof
Solution 1:
Your __sizeof__
is getting called, it's just adding the garbage collector overhead to it which is why the result isn't zero.
From the docs on sys.getsizeof
:
getsizeof()
calls the object’s__sizeof__
method and adds an additional garbage collector overhead if the object is managed by the garbage collector.
Returning 0
is one way in which you make it hard for your self to understand that it's called since you'll always get the same result back (0
+ overhead).
Return a size based on the contents of the dynamic array to see it change.
To further elaborate:
Each object in CPython has some administrative information attached to it in a PyGC_head
struct that gets added:
/* add gc_head size */if (PyObject_IS_GC(o))
return ((size_t)size) + sizeof(PyGC_Head);
return (size_t)size;
that is used by the garbage collector.
Why this is added to the overall size is probably because it does represent additional memory required by the object. On the Python level, you don't need to worry about the collection of garbage and treat it all like magic, but, when asking for information on the size of an object you should not sacrifice correct results just to keep the illusion alive.
Post a Comment for "__sizeof__ Not Getting Called By Sys.getsizeof"