Don't use __slots__ (was Re: performance of dictionary lookup vs. object attributes)

Patrick Maupin pmaupin at gmail.com
Sun Aug 27 20:52:26 EDT 2006


Jacob Hallen wrote:
> Patrick Maupin <pmaupin at gmail.com> wrote:
> >Also, as I noted, I _do_ use them on occasion, so if there really _are_
> >potential pitfalls there, I would like to understand exactly what they
> >are, so my ears perk up whenever I notice a __slots__ discussion, but
> >so far I have been repeatedly disappointed, in that I always see
> >someone saying "don't do that" but I have never seen a cogent technical
> >argument about how my scripts which __slots__ are going to suddenly,
> >irretrievably break one day.
>
> The proper use of__slots__is to save space in objects. Instead of having
> a dynamic dict that allows adding attributes to objects at anytime,
> there is a static structure which does not allow additions after creation.
> This saves the overheadof one dict for every object that uses slots.
> While this is sometimes a useful optimisation, it would be completely
> unnecessary if the Python interpreter was dynamic enough so that it would
> only require the dict when there actually were additions to the object.
>
> Unfortunately there is a side effect to slots. They change the behaviour of
> the objects that have slots in a way that can be abused by control freaks
> and static typing weenies. This is bad, because the contol freaks should
> be abusing the metaclasses and the static typing weenies should be abusing
> decorators, since in Python,there should be only one obvious way of doing something.
>
> Making CPython smart enough to handle saving space without __slots__ is a a major
> undertaking, which is probably why it is not on the list of changes for P3k (yet).
>
> Jacob Hallén

Thanks, Jacob!

Saving space is exactly why I use __slots__, so I can sleep better now
:)

Regards,
Pat




More information about the Python-list mailing list