__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
- Instances get fixed storage, so a typo raises instead of sticking.
- It saves real memory when you have many small objects.
- Subclasses need their own slots to keep the benefit.
Keywords and builtins used here
Pointasclassdefexcepthasattrprintselftry
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.
Step 1 of 3 in Attributes & descriptors, step 32 of 53 in Pythonic Python.