Don't use __slots__
Hrvoje Niksic
hniksic at xemacs.org
Mon Oct 8 15:50:52 EDT 2007
Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:
> 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:
[...]
> But is there actually anything *harmful* that can happen if I use
> __slots__?
Here is one harmful consequence: __slots__ breaks multiple
inheritance:
class A(object):
__slots__ = ['a', 'b']
class B(object):
__slots__ = ['c']
class AB(A, B):
pass
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
multiple bases have instance lay-out conflict
Even if A and B had the exact same slots, for example ['a', 'b'], it
wouldn't make a difference. AB explicitly setting __slots__ to
something like ['a', 'b', 'c'] doesn't help either. But that is only
a technical answer to your technical question which misses the real
problem people like Aahz and Guido have with __slots__. (I don't
claim to represent them, of course, the following is my
interpretation.)
The backlash against __slots__ is a consequence of it being so easy to
misunderstand what __slots__ does and why it exists. Seeing __slots__
has led some people to recommend __slots__ to beginners as a way to
"catch spelling mistakes", or as a way to turn Python's classes into
member-declared structures, a la Java. For people coming from Java
background, catching mistakes as early as possible is almost a dogma,
and they are prone to accept the use of __slots__ (and living with the
shortcomings) as a rule.
Python power users scoff at that because it goes against everything
that makes Python Python. Use of __slots__ greatly reduces class
flexibility, by both disabling __dict__ and __weakref__ by default,
and by forcing a tight instance layout that cripples inheritance.
With people using __slots__ for the majority of their classes, it
becomes much harder for 3rd-party code to attach an unforeseen
attribute to an existing object. Even with single inheritance,
__slots__ has unintuitive semantics because subclasses automatically
get __dict__ and __weakref__, thereby easily breaking the "benefits"
of their use.
__slots__ is a low-level tool that allows creation of dict-less
objects without resorting to Python/C. As long as one understands it
as such, there is no problem with using it.
More information about the Python-list
mailing list