I'm trying to subclass primitive types in Python like this (simplified version):
class MyInt(int):
pass
I thought that an object of this class would take the same amount of memory as the primitive one. But, apparently, that's not true:
import sys
sys.getsizeof(10) # 24
sys.getsizeof(MyInt(10)) # 72
Using __slots__, I was able to save some memory, but the subclass still takes more space:
class MyInt(int):
__slots__ = ()
sys.getsizeof(10) # 24
sys.getsizeof(MyInt(10)) # 56
If I subclass my own classes, on the other hand, the memory usage is the same:
class Father(object):
pass
class Son(Father):
pass
sys.getsizeof(Father()) # 64
sys.getsizeof(Son()) # 64
- Why does the subtype object use more memory than the primitive type object, if there are no extra fields?
- Is there a way to prevent (or minimize) this?
I'm using Python 2.7.12.
__new__and look up the instance in a dictionary instead of creating a new one.MyIntin the first place?