PYTHON

Create Memory-Efficient Data Classes with __slots__

Design Python data structures that save memory and potentially offer faster attribute access using `__slots__`, useful for creating many small, fixed-attribute objects.

import sys

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

class DataPointWithSlots:
    __slots__ = ('x', 'y', 'label') # Define allowed attributes
    def __init__(self, x, y, label):
        self.x = x
        self.y = y
        self.label = label

# Create instances
point_no_slots = DataPointWithoutSlots(10, 20, 'A')
point_with_slots = DataPointWithSlots(10, 20, 'A')

print(f"Size of DataPointWithoutSlots: {sys.getsizeof(point_no_slots)} bytes")
print(f"Size of DataPointWithSlots: {sys.getsizeof(point_with_slots)} bytes")

# Accessing attributes works the same way
print(f"No slots label: {point_no_slots.label}")
print(f"With slots label: {point_with_slots.label}")

# Attempting to add a new attribute to a __slots__ class will raise AttributeError
try:
    point_with_slots.z = 30
except AttributeError as e:
    print(f"Error adding new attribute to __slots__ class: {e}")
How it works: This snippet illustrates how to use `__slots__` in Python classes to create more memory-efficient data structures. By defining `__slots__`, you explicitly tell Python which attributes an instance can have. This prevents the creation of an instance dictionary (`__dict__`) for each object, leading to significant memory savings, especially when creating a large number of instances. It can also slightly speed up attribute access. Additionally, `__slots__` prevents the creation of new attributes dynamically on instances, which can help in maintaining a strict data schema for your objects.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs