Use of __slots__

Delaney, Timothy (Tim) tdelaney at avaya.com
Sun Feb 26 18:05:16 EST 2006


Steve Juranich wrote:

> IMHO, __slots__ is unpythonic.  Many others have stated so on the
> list. That's why it's great that you're free to ignore that variable.
> I suggest that you do so (as I have chosen to do).  I'm sure that
> there are situations where you *MUST* have this kind of capability,
> but I haven't bumped into them yet.

In general, I would agree that __slots__ is unpythonic. And I can state
categorically that there is *no* situation where __slots__ is actually
required - everything semantically that __slots__ does (including the
incidental restriction of attributes) can be done via other mechanisms.

That being said ... there *are* use cases for __slots__ (otherwise it
would not exist ;) Specifically, __slots__ is a memory and performance
optimisation. One you should almost never use.

In my self.super recipe
<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286195>, use of
__slots__ made a measurable difference in performance - and since my aim
was to replace `super(cls, self)` with `self.super`, getting as close to
the performance of `super(cls, self)` was important.

Eventually of course, I achieved my best results using Pyrex and
on-the-fly bytecode modification ... interestingly, the fastest approach
I could find with Python (excluding the bytecode modifications) was
slightly different to the fastest approach in Pyrex.

Tim Delaney



More information about the Python-list mailing list