Optimization of Data Classes
00:00 Optimizing data classes. In this section of the course, you’re going to take a look at slots, which can be used to make classes faster and take up less memory.
00:11 Data classes have no explicit syntax for working with slots, but the normal way of creating them works for data classes as well. You probably expect this as, after all, data classes are really just regular classes.
00:59
In essence, slots are defined using the .__slots__
to list the variables on a class. Variables or attributes not present in the .__slots__
list may not be defined. Furthermore, a slots class may not have default values.
01:16 The benefit of adding such restrictions is that optimizations can be performed. For instance, slots classes take up less memory, as can be measured using Pympler.
02:08
Similarly, slots classes are typically faster to work with. The following example measures the speed of attribute access on a slots data class and a regular data class using timeit
from the standard library.
03:04 In this particular example, the slot class is about 20% faster. So now that you’ve learned a great deal about data classes, let’s sum up everything that you’ve covered.
Become a Member to join the conversation.
mp on April 28, 2023
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):
Looks like the slots parameter was added in 3.10 (this course was earlier, using 3.9). docs.python.org/3/library/dataclasses.html