4

Take the following example:

from foo import Bar

b = Bar
print(b.__slots__)
#Stack trace, no attribute __slots__

Assume then that we want to add a __slots__ attribute because lots (and lots) of Bar instances will be created.

from foo import Bar

CBar = Bar
CBar.__slots__ = ["one", "two", "three"]

b = CBar
print(b.__slots__)
#Success

b.four = 0
print(b.four)
#Prints 0....hmmm....

Is it possible to import a class from a module and add __slots__ attribute dynamically?

Konstantin
  • 24,271
  • 5
  • 48
  • 65
Jzl5325
  • 3,898
  • 8
  • 42
  • 62
  • I don't know this for sure, but it would surprise me greatly if you were able to swap out `__dict__`s for `__slots__`s at runtime, if only because of the magic involved in making that distinction. – Adam Smith Jun 10 '15 at 03:16
  • 1
    @AdamSmith is correct (see [this answer](http://stackoverflow.com/a/10822309/429982) for some limitations on using `__slots__`). That doensn't mean you can't create a brand new class though that mostly acts like `Bar`, but does have a `__slots__` on it (but it might require a bit of effort :)) – Gerrat Jun 10 '15 at 03:21
  • 1
    As of Python 3.3, [instances of the same class will use a shared dict](https://www.python.org/dev/peps/pep-0412/), so using `__slots__` as a memory saving technique becomes less useful. – Gerrat Jun 10 '15 at 03:33
  • I know, that the link leads to a question regarding `__slots__` in Python 3, but answer by Martijn Pieters applies to Python 2.7 as well – Konstantin Jun 10 '15 at 05:58
  • @Alik I went ahead and marked as a duplicate as the linked answer does pertain to 2.x as well. Can the 2.x tag be added to that question so it pops on a search / question start? – Jzl5325 Jun 10 '15 at 13:15

0 Answers0