Using __slots__ to save storage
The default behavior of the object
superclass is to create a dict
for an object's attributes. This provides fast resolution of names. It means that an object can have attributes added and changed very freely. Because a hash is used to locate the attribute by name, the internal dict
object can consume quite a bit of memory.
We can modify the behavior of the object
superclass by providing a list of specific attribute names when we create a class. When we assign these names to the specially named __slots__
variable, these will be the only available attributes. A dict
is not created, and memory use is reduced considerably.
If we're working with very large datasets, we might need to use a class that looks like this:
class ...
Get Python Essentials now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.