Using python __slots__ for memory improvement

__slots__

By Marcelo Fernandes Aug 20, 2017

Play Ground

Ps: Only use __slots__ if you have been creating a lot of instances of a single class. There are problems involving hierarchy that might be hard to solve if this practice is propagated over the entire code.

Normal Class Declaration


import resource


class Foo(object):
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

foos = [Foo(a=foo, b=foo+1, c=foo+2) for foo in range(1000000)]

print('Memory usage: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
# Memory usage: 277520 (kb)

Using __slots__


import resource


class Bar(object):
 	__slots__ = ('a', 'b', 'c')
 	def __init__(self, a, b, c):
 		self.a = a
 		self.b = b
 		self.c = c

bars = [Bar(a=bar, b=bar+1, c=bar+2) for bar in range(1000000)]
print('Memory usage: %s (kb)' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
# Memory usage: 174260 (kb)


Notes