[PYTHON] Save memory with `` __slots__``

I didn't know it, so make a note.

By default, Python uses dict to store the attributes of an instance of an object. With this saving method, new attributes may be set dynamically during execution.

But dict is a waste of memory when dealing with small classes with a small number of fixed attributes. In such a case, it is better to save memory by writing the name of the attribute in __slots__.

class Image(object):
    __slots__ = ['id', 'caption', 'url']

    def __init__(self, id, caption, url):
        self.id = id
        self.caption = caption
        self.url = url
        self._setup()

        # ... other methods ...

reference

Recommended Posts

Save memory with `` __slots__``
Use shared memory with shared libraries
Save images with web scraping
Save tweet data with Django
Investigate memory leaks with objgraph
Save & load data with joblib, pickle
Save and retrieve files with Pepper
Send image with python, save with php
Save video frame by frame with Python OpenCV
Edit and save read-only files with vim
Save / load in-memory DB with python sqlite3
Record with Python → Save file (sounddevice + wave)
What I did to save Python memory