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-constrained environments, optimizing class memory usage can be crucial. One often overlooked technique is utilizing the __slots__ attribute in Python classes. By declaring __slots__, you can significantly reduce the memory footprint of your objects.

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_obj = RegularClass(1, 2)
slotted_obj = SlottedClass(1, 2)

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

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

Takeaway: By leveraging __slots__ in your Python classes, you can minimize memory usage and improve performance, especially when dealing with large numbers of objects. Remember to use __slots__ when you have a fixed set of attributes and don't need dynamic attribute assignment.


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


If you found this useful, you might like Python Interview Prep Guide — a practical resource that takes things a step further. At $24.99 it's a solid investment for your toolkit.

Top comments (0)