Don't use __slots__ (was Re: Problem of Readability of Python)

Diez B. Roggisch deets at
Mon Oct 8 16:07:36 CEST 2007

Steven D'Aprano wrote:

> On Mon, 08 Oct 2007 15:15:36 +0200, Diez B. Roggisch wrote:
>>> Well, I've read the thread, and I've read the thread it links to, and
>>> for the life of me I'm still no clearer as to why __slots__ shouldn't
>>> be used except that:
>>> 1 Aahz and Guido say __slots__ are teh suxxor;
>>> 2 rumour (?) has it that __slots__ won't make it into Python 3.0;
>>> 3 inheritance from classes using __slots__ doesn't inherit the slot-
>>> nature of the superclass.
>>> Point 1 is never to be lightly dismissed, but on the other hand Guido
>>> doesn't like reduce(), and I'm allergic to "Cos I Said So" arguments.
>>> History is full of things which were invented for one purpose being
>>> used for something else. So, that being the case, suppose I accept that
>>> using __slots__ is not the best way of solving the problem, and that
>>> people of the skill and experience of Guido and Aahz will roll their
>>> eyes and snicker at me.
>>> But is there actually anything *harmful* that can happen if I use
>>> __slots__?
>> Point 3 clearly is harmful.
> No, it is DIFFERENT, not harmful. At worst, it's a "gotcha" -- a really
> well-documented gotcha.

To the casual observer? I doubt it. I wasn't aware of that until a recent
discussion about slots. But then, I've so far _never_ felt the need to  use
>> As is the fact that __slots__ gives you
>> troubles if you e.g. pass objects to code that tries to set arbitrary
>> attributes on an object.
> You mean like this?
>>>> x = 1
>>>> x.label = "foo"
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: 'int' object has no attribute 'label'
> I guess that means ints and floats and strings and tuples and lists are
> all harmful too, yes?

You are very well aware that I was talking about complex objects. And I
didn't say that they are harmful, but that using __slots__ to constrain
object attribute will lead to surprising results here in comparison to
the "usual" behavior. And with usual I mean
most-of-the-classes-work-that-way. Which might be considered as reason to
_not_ do it. But you are free to limit yourself, be my guest.

>> The question is: what does a slot buy you for this kind of problem?
> Simplicity and explicitness.

Where is that more simple? Additional notation that will lead to
runtime-errors, the same way misspelled attribute-names do?

And yes, it is more explicit. As are interfaces, and type declarations. 


More information about the Python-list mailing list