DEV Community

qing
qing

Posted on

Quick Python Tip: Use __slots__ to Reduce Class Memory Usage (2026)

Quick Python Tip: Use slots to Reduce Class Memory Usage

When working with large datasets or memory-intensive applications, optimizing class memory usage can significantly improve performance. One often overlooked feature in Python is the __slots__ attribute, which allows you to explicitly declare data attributes and reduce memory consumption.

Let's compare the memory usage of a regular class versus one using __slots__:

import sys

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

class SlottedClass:
    __slots__ = ('x', 'y')
    def __init__(self, x, y):
        self.x = x
        self.y = y

regular_instance = RegularClass(1, 2)
slotted_instance = SlottedClass(1, 2)

print(sys.getsizeof(regular_instance))  # Output: 56 (varies by Python version)
print(sys.getsizeof(slotted_instance))  # Output: 40 (varies by Python version)
Enter fullscreen mode Exit fullscreen mode

As shown, using __slots__ reduces the memory usage of the SlottedClass instance by approximately 30% compared to the RegularClass instance.

Takeaway: By using __slots__ to declare data attributes, you can significantly reduce class memory usage, leading to improved performance and efficiency in memory-intensive applications. Remember to use __slots__ when you have a large number of instances or when working with limited memory resources.


Follow me on Dev.to for daily Python tips and quick guides!

Top comments (0)