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

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Oct 8 09:26:31 EDT 2007


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.


> 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?



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

Simplicity and explicitness.



-- 
Steven.



More information about the Python-list mailing list