Free Online Code Editor
Optimize memory usage with __slots__.
# Regular class
class RegularPoint:
def __init__(self, x, y):
self.x = x
self.y = y
# Class with __slots__
class OptimizedPoint:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
# Create instances
regular = RegularPoint(1, 2)
optimized = OptimizedPoint(1, 2)
# Memory comparison
import sys
print(f"Regular point size: {sys.getsizeof(regular)} bytes")
print(f"Regular point dict: {sys.getsizeof(regular.__dict__)} bytes")
print(f"Optimized point size: {sys.getsizeof(optimized)} bytes")
# Regular class allows dynamic attributes
regular.z = 3
print(f"\nRegular with z: {regular.z}")
# Optimized class does not
try:
optimized.z = 3
except AttributeError as e:
print(f"\nOptimized error: {e}")
# Multiple instances comparison
regulars = [RegularPoint(i, i) for i in range(1000)]
optimizeds = [OptimizedPoint(i, i) for i in range(1000)]
regular_total = sum(sys.getsizeof(p) + sys.getsizeof(p.__dict__) for p in regulars)
optimized_total = sum(sys.getsizeof(p) for p in optimizeds)
print(f"\n1000 regular points: {regular_total:,} bytes")
print(f"1000 optimized points: {optimized_total:,} bytes")
print(f"Savings: {regular_total - optimized_total:,} bytes")
# __slots__ with inheritance
class Base:
__slots__ = ['x']
class Derived(Base):
__slots__ = ['y']
def __init__(self, x, y):
self.x = x
self.y = y
point = Derived(1, 2)
print(f"\nDerived point: x={point.x}, y={point.y}")__slots__ restricts attributes to save memory. No __dict__ created. Faster attribute access. Cannot add dynamic attributes. Use for many instances.