[Python-Dev] Make it an error to use __slots__ with classic classes

Raymond Hettinger python at rcn.com
Sat Aug 9 04:10:47 EDT 2003

> Raymond Hettinger writes:
>  > Using __slots__ with a classic class is an error that does
>  > not readily reveal itself.  For Py2.3.1, I would like to 
>  > issue a warning, and for Py2.4, I would like to
>  > raise an exception upon class creation:

[Mr. Fred]
> You'll need to explain your motivation a bit more.  Why is it an error
> to define __slots__ on an old-style class?  (Useless perhaps, but why
> an error?)

Everytime I've seen this occur, the author had intended for
__slots__ to actually be working to save memory by having
lighter weight objects.  However, since memory usage is
not immediately visible, the programming error would go

The risk is even higher when subclassing is used.  Quick, is
__slots__ working in this code:

import random
class MarkovPair(random.Random):
   __slots__ = ['current_variate', 'previous_variate']
   . . .

In my PyZine article, my first draft included an erroneous __slots__ 
example which did not inherit from object.  The code and tests ran
fine -- luckily, one alert reviewer caught it.  I would have appreciated
an exception being raised.  Likewise, a recent poster on comp.lang.python
had the same experience.  Whereever __slots__ are used with old
style classes, there is a super high probability that the author intended
the code to behave differently than it actually does.

Raymond Hettinger

P.S.  The answer to the quick look question above is that
__slots__ has no effect in Py2.2 but does in Py2.3
because one is an old-style class written in pure python
and the other is a new-style class derived from the
MersenneTwister type.

More information about the Python-Dev mailing list