DEV Community

Cover image for Python Trick: The Magic of __slots__
Developer Service
Developer Service

Posted on

Python Trick: The Magic of __slots__

Python’s flexibility with dynamic attributes is one of its strengths, but sometimes you want to optimize memory usage and performance.

Enter slots, a feature that allows you to define a fixed set of attributes for your class, reducing memory overhead and potentially speeding up attribute access.


How It Works

Normally, Python objects are implemented as dictionaries for storing attributes, which can lead to higher memory consumption.

By defining slots in your class, you instruct Python to use a more memory-efficient internal structure.

This is especially useful when you know the attributes a class will have ahead of time and want to avoid the overhead of a full dictionary.

Here’s a demonstration of how to use slots:

class Point:
    __slots__ = ['x', 'y']  # Define the allowed attributes

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


# Create a Point instance
p = Point(10, 20)

print(p.x)  # Output: 10
print(p.y)  # Output: 20

# Attempting to add a new attribute will raise an AttributeError
try:
    p.z = 30
except AttributeError as e:
    print(e)  # Output: 'Point' object has no attribute 'z'

# Output:
# 10
# 20
# 'Point' object has no attribute 'z'
Enter fullscreen mode Exit fullscreen mode

In this example, slots restricts the Point class to only the x and y attributes.

Attempting to set any attribute not listed in slots results in an AttributeError.


Why It’s Cool

Using slots can lead to significant memory savings, especially when creating large numbers of instances, by eliminating the overhead of the attribute dictionary.

It can also improve attribute access speed.

However, be cautious: slots can limit some dynamic capabilities of Python objects and may not be suitable for all use cases.

Top comments (0)