Revision 5 as of 2022-02-22 15:04:45

Clear message

Introduction

__slots__ has a mixed reputation in the Python community. On the one hand, they are considered to be popular. Lots of people like using them. Others say that they are badly understood, tricky to get right, and don't have much of an effect unless there are many instances of objects that use them. This article will explain what they are, how, and why to use them, and when not to use them.

What Is `__slots__` ?

__slots__ are discussed in the Python Language Reference under section 3.3.2, Customizing Attribute Access. The first thing we should understand is that __slots__ is only used in the context of Python classes. __slots__ is a class variable that is usually assigned a sequence of strings that are variable names used by instances. For example:

    class Example():
    __slots__ = ("slot_0", "slot_1")
    
    def __init__(self):
        self.slot_0 = "zero"
        self.slot_1 = "one"
        
x1 = Example()
print(x1.slot_0)
print(x1.slot_1)

    zero
    one

The __slots__ declaration allows us to explicitly declare data members, causes Python to reserve space for them in memory, and prevents the creation of __dict__  and __weakref__ attributes. It also prevents the creation of any variables that aren't declared in __slots__.

Why Use `__slots__`?

The short answer is slots are more efficient in terms of memory space and speed of access, and a bit safer than the default Python method of data access. By default, when Python creates a new instance of a class, it creates a __dict__ attribute for the class. The __dict__ attribute is a dictionary whose keys are the variable names and whose values are the variable values. This allows for dynamic variable creation but can also lead to uncaught errors. For example, with the default __dict__, a misspelled variable name results in the creation of a new variable, but with __slots__ it raises in an AttributeError.

class Example2():
    
    def __init__(self):
        self.var_0 = "zero"
        
x2 = Example2()
x2.var0 = 0

print(x2.__dict__.keys())
print(x2.__dict__.values())
```

    dict_keys(['var_0', 'var0'])
    dict_values(['zero', 0])



```python
x1.slot1 = 1
```


    ---------------------------------------------------------------------------

    AttributeError                            Traceback (most recent call last)

    Input In [3], in <module>
    ----> 1 x1.slot1 = 1


    AttributeError: 'Example' object has no attribute 'slot1'

As mentioned earlier, a __slots__ declaration uses less memory than a dictionary, and direct memory access is faster than dictionary lookups. __slots__ variables use dot notation for assignment and referencing in exactly the same way as the default method. But it should be noted that attempting to access the __slots__ tuple by subscription returns only the name of the variable.

Unable to edit the page? See the FrontPage for instructions.