Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Optimization of Data Classes

I hadn’t heard of slots before. I tried messing around with this afterwards, I found that I couldn’t set defaults when slots had been defined. But then further messing around, it seems that now you don’t even have to declare slots manually (at least if all fields are to use slots):

@dataclass(frozen=True, slots=True)
class Position:
    name: str
    longitude: float = 0.0
    latitude: float = 0.0

pos = Position("oslo", 5, 10)

>>> pos.__slots__
('name', 'longitude', 'latitude')

Looks like the slots parameter was added in 3.10 (this course was earlier, using 3.9). docs.python.org/3/library/dataclasses.html

Become a Member to join the conversation.