6

This is explicitly documented in the reference manual:

Nonempty _slots_ does not work for classes derived from “variable-length” built-in types such as int, bytes and tuple.

and it is the case, writing:

class MyInt(int):
    __slots__ = 'spam',

results in:

TypeError: nonempty __slots__ not supported for subtype of 'int'

why is this, though? Why can empty slots be used but non empty ones forbidden?

S.B
  • 13,077
  • 10
  • 22
  • 49
Bob Holver
  • 277
  • 1
  • 9

1 Answers1

5

__slots__ reserves space at a fixed offset in an object’s layout for each slot defined. (This is how it avoids having a __dict__ in which to store them.) A variable-length object could have a fixed-length prefix before its variable-size data, but when deriving from such a type there’s no available fixed offset at which to add a slot. Since part of the purpose of __slots__ is fast lookup, it doesn’t make much sense to teach it how to look past the end of the variable-length data. __dict__, however, does have such support, so it’s meaningful to suppress it with __slots__=().

Davis Herring
  • 36,443
  • 4
  • 48
  • 76