Search code examples
pythonslots

Add an attribute to an object which uses __slots__


I want to add an attribute to an object which uses slots. I know this is a hack and should not be used.

But is there a way to get around this restriction of slots?


Solution

  • You can kind of modify __slots__ by creating a subclass with the same name and then replacing parent class with its child. Note that you can do this for classes declared and used in any module, not just yours!

    Also note that this question has been answered a few times already. See my answer here for more details.
    (actually there was no my answer at the time you asked, but there were questions with other answers =)) )