Simon Engledew's Blog

Eldritch nomenclature, conjoured for arcane contraptions to execute unerringly.

July 7, 2009 at 10:42am
home

Python Slots

I just got clued in by Elf Sternberg’s Blog to a really useful feature in Python that I have never heard about before, slots:

class Foo(object):
    __slots__ = ['x']
    def __init__(self, n):
        self.x = n

From the Python reference manual:

“By default, instances of both old and new-style classes have a dictionary for attribute storage. This wastes space for objects having very few instance variables. The space consumption can become acute when creating large numbers of instances.

The default can be overridden by defining slots in a new-style class definition. The slots declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because dict is not created for each instance.”

At work we have a plans engine that loads millions of little Python objects into memory, so this is a great little optimisation for us.

Finally, to get a set of every slot attribute in the object hierarcy, you can add this method to your class:

def inherited_slots(self):
        return set(slot for klass in self.__class__.__mro__ if hasattr(klass, '__slots__') for slot in klass.__slots__)