Slots Optimization in Python

Level 5349 keystrokes

This shows __slots__ for memory optimization. Slotted classes use less memory by avoiding instance __dict__ creation.

Python code

# RegularPoint is a normal class
# Has __dict__ for storing attributes dynamically
1class RegularPoint:
# __init__ sets x and y coordinates
# Creates entries in instance __dict__
2 def __init__(self, x: int, y: int):
3 self.x = x
4 self.y = y
5
# SlottedPoint uses __slots__ for optimization
# No __dict__ is created, saving memory
6class SlottedPoint:
# __slots__ defines fixed set of attributes
# Only x and y can be stored on instances
7 __slots__ = ("x", "y")
8
# __init__ sets same attributes as RegularPoint
# But stores in slots instead of __dict__
9 def __init__(self, x: int, y: int):
10 self.x = x
11 self.y = y
12
# Import sys for memory size checking
13import sys
# Create instance of regular class
14regular = RegularPoint(1, 2)
# Create instance of slotted class
15slotted = SlottedPoint(1, 2)
16
# Show size of regular instance's __dict__
# __dict__ takes extra memory for attribute storage
17print(f"Regular: {sys.getsizeof(regular.__dict__)} bytes dict")
# Slotted instances have no __dict__
# Attributes stored directly in slots
18print(f"Slotted has no __dict__")

Output

Regular: 64 bytes dict
Slotted has no __dict__
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • _× 20
  • :× 9
  • "× 8
  • (× 8
  • )× 8
  • ,× 7
  • =× 7
  • .× 6
  • {× 1
  • }× 1

More Python examples at level 5

← Python typing practice