__slots__ replacing __dict__ function

Alex Martelli aleax at aleax.it
Thu Nov 6 04:16:58 EST 2003


anabell at sh163.net wrote:

> I have a code like this:
> 
>        sqlString = 'INSERT INTO ' + self.TableName + ' VALUES (' +
>        self.TableFields + ')' self.cursor.execute(sqlString,
>        self.__dict__)
> 
> This works correctly.  However, I'm applying __slots__ in my script.  And
> doing so would need the above statement modified.  How will __slots__
> perform the same task defined above?
> 
> Is there a container that holds the values of attributes contained in
> __slots__?  In __dict__, you have (attribute: value) pair.

Each instance you have simultaneously alive that is using __slots__
and therefore saving the per-instance __dict__ will save you a few
tens of bytes -- say, optimistically, 64 bytes if you have quite a
few attributes per instance.

Will you have as many as, say, 100,000 instances simultaneously
alive, and, if so, will saving about 6 MB of memory be crucially
important to your application's performance?

For a typical class that's unlikely to exist in more than a few
thousands of instances alive at a time, saving a few tens of KB
of memory is an absolutely derisory benefit and will emphatically
_NOT_ repay the extra programming effort to use __slots__.

Have you performed this back-of-the-envelope estimate?  Is the
use of __slots__ truly justified in your case?

Don't use __slots__ just to try and get back closer to the
behavior of some other language you're used to -- or else you'll
get back all the _hassles_ typical of those other languages,
fully including more laborious reflection and introspection.


Alex





More information about the Python-list mailing list