-1

I have the following code in Python 2.7:

>>> class A(object):
...     pass
... 
>>> class B(A):
...     __slots__ = tuple()
... 
>>> b = B()
>>> b.x = 1
>>> b.y = 2

Does that mean the __slots__ in the subclass B is basically useless, because it does not prevent dynamic attribute creation?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
David Zheng
  • 797
  • 7
  • 21
  • Related: [Python: How does inheritance of \_\_slots\_\_ in subclasses actually work?](http://stackoverflow.com/q/1816483) – Martijn Pieters Jun 25 '15 at 21:01
  • 1
    And you should **not** rely on `__slots__` preventing dynamic attributes. That's not what `__slots__` are *for*. They are meant to limit the amount of memory instances require. – Martijn Pieters Jun 25 '15 at 21:02
  • Hi, @jonsharpe. I have a followup question after reading the doc. The use of \__slots__ is to save memory, which is achieved by removing the dictionary \__dict__ for attribute storage. If the space allocated for the attributes that're assigned to \__slots__ is bigger than the space saved, does that mean setting \__slots__ is meaningless? – David Zheng Jun 25 '15 at 21:39
  • That doesn't make sense; give that the same attribute values would be stored in the dictionary `__dict__` as you're storing using `__slots__`, how could that *ever* be the case? You're *always* saving the space that the dictionary itself would have taken up. Also note that I don't get notified if you spell my username wrongly! – jonrsharpe Jun 25 '15 at 21:49
  • A dictionary object over-allocates and will *always* take up more space than the slots. – Martijn Pieters Jun 25 '15 at 21:50
  • @jon but you always get notified for comments on your own posts. Which is why your name isn't even available for auto-completion and got misspelled in the first place :-) – Martijn Pieters Jun 25 '15 at 21:52
  • @MartijnPieters yes, if the OP had commented on the answer I would have been pinged. Is autocomplete not available for editors' names, even though they're eligible for notifications? – jonrsharpe Jun 25 '15 at 21:57
  • @jon: Ah, missed that this is *question* (I am on mobile at the moment). No, editor names are not available for auto-completion either. – Martijn Pieters Jun 25 '15 at 22:00
  • Thanks, guys. I got the idea now. – David Zheng Jun 25 '15 at 22:11

1 Answers1

2

Per the documentation:

When inheriting from a class without __slots__, the __dict__ attribute of that class will always be accessible, so a __slots__ definition in the subclass is meaningless.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437