typestar

__slots__ in Python

Declaring the attributes up front drops the per-instance dict.

class Point:
    __slots__ = ("x", "y")

    def __init__(self, x, y):
        self.x = x
        self.y = y


p = Point(1.5, 2.5)
print(p.x, p.y, Point.__slots__)

try:
    p.z = 3
except AttributeError as exc:
    print("rejected:", exc)
print(hasattr(p, "__dict__"))

How it works

  1. Instances get fixed storage, so a typo raises instead of sticking.
  2. It saves real memory when you have many small objects.
  3. Subclasses need their own slots to keep the benefit.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
237
Tokens
87
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 50 seconds.

Type this snippet

Step 1 of 3 in Attributes & descriptors, step 32 of 53 in Pythonic Python.

← Previous Next →