PYTHON
Optimize Object Memory with __slots__
Learn how to use __slots__ in Python classes to reduce memory consumption and speed up attribute access, vital for scalable web applications.
import sys
class UserWithoutSlots:
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
class UserWithSlots:
__slots__ = ('name', 'email', 'age')
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
# Create instances
user_no_slots = UserWithoutSlots('Alice', '[email protected]', 30)
user_with_slots = UserWithSlots('Bob', '[email protected]', 25)
# Compare memory usage
print(f"Memory usage of UserWithoutSlots: {sys.getsizeof(user_no_slots)} bytes")
print(f"Memory usage of UserWithSlots: {sys.getsizeof(user_with_slots)} bytes")
# Access attributes (typically faster with slots)
print(f"User without slots: {user_no_slots.name}, {user_no_slots.email}")
print(f"User with slots: {user_with_slots.name}, {user_with_slots.email}")
# Trying to add a new attribute to a __slots__ class (will raise AttributeError)
# try:
# user_with_slots.address = '123 Main St'
# except AttributeError as e:
# print(f"Error adding new attribute to UserWithSlots: {e}")
How it works: The `__slots__` attribute in Python classes allows you to explicitly declare instance variables, preventing the automatic creation of `__dict__` for each object. By doing so, `__slots__` significantly reduces the memory footprint of objects, especially when you have a large number of instances of a class. It also slightly speeds up attribute access. While `__slots__` restricts the ability to add new attributes dynamically to instances, it's a powerful optimization technique for data-heavy applications, such as ORMs, API response models, or any scenario where memory efficiency is critical for web application performance and scalability.