Looking for a way to decrease the use of memory in python, I created this code
from pympler.asizeof import asizeof
class Reduce(type):
def __new__(cls, name, bases, attrs):
attrs['__dict__'] = {}
return super().__new__(cls, name, bases, attrs)
class WithReduce(metaclass=Reduce):
def __init__(self):
self.a = 1
class Normal:
def __init__(self):
self.a = 1
print(asizeof(WithReduce())) # 122
print(asizeof(Normal())) # 240
I was able to reduce the memory usage of the class by almost 50% excluding the content of __dict__
in the metaclass.
In some tests I realized that, when adding new attributes in the WithReduce
, they do not take up space in memory and are not stored in __dict__
. However, in the Normal
they occupy memory and are stored in __dict__
a = WithReduce()
b = Normal()
print(asizeof(a)) # 122
print(asizeof(b)) # 240
a.foo = 100
b.foo = 100
print()
print(asizeof(a)) # 112
print(asizeof(b)) # 328
print()
print(a.__dict__) # {}
print(b.__dict__) # {'a': 1, 'foo': 100}
Knowing this, I had two doubts.
Why didn't
WithReduce
take up more memory by adding a variable to it?Where is the variable is added in
WithReduce
?