Sobes.tech
Junior — Middle

Can you explain what __slots__ in Python is and how it affects object memory management?

sobes.tech AI

Answer from AI

__slots__ in Python is a mechanism that allows you to restrict the set of attributes that instances of a class can have, thereby optimizing memory usage.

By default, each Python object stores its attributes in a dictionary (__dict__), which consumes additional memory. If you define __slots__ in a class, Python does not create a dictionary for each instance but allocates a fixed space for the specified attributes.

Example of usage:

class Point:
    __slots__ = ('x', 'y')  # only these attributes are allowed

    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(1, 2)
print(p.x, p.y)  # 1 2

# p.z = 3  # will raise AttributeError because 'z' is not in __slots__

Thus, __slots__ reduces memory consumption and can slightly speed up attribute access, but it restricts the dynamic addition of new attributes.