1

EDIT : People saying its a duplicate of Python: How does inheritance of __slots__ in subclasses actually work?. It is not. The accepted answer of the the above question doesn't even help or make me understand it a bit. But the answer I accepted, says that Usage of __slots__? has the answer I want inside it, which could be true.

While coding the following block got me stuck. Is there any place where Python ignores __slots__?

Assume a demo code as follows. (GObject is an abstract object which is used in making Gtk widgets.)


class A:

    __slots__ = ("x", "y")

    def __init__(self, x, y):
        self.x = x
        self.y = y

class B(A):

    __slots__ = ("z",)

    def __init__(self, x, y, z):
        super().__init__(x, y)
        self.z = z

class C(A):

    __slots__ = ("w",)

    def __init__(self, x, y, z):
        super().__init__(x, y)
        self.z = z

class D(GObject.Object):

    __slots__ = ("w",)

    def __init__(self, z):
        super().__init__()
        self.z = z
b = B(1, 2, 3)
#c = C(1, 2, 3) # Results in AttributeError: 'C' object has no attribute 'z'
d = D(10) # No Error! ^^

#b.p = 3 # AttributeError
d.p = 3 # No Error ^*

Please explain the reason why D doesn't get any AttributeError.

J Arun Mani
  • 620
  • 3
  • 20
  • Thats what I'm asking. No its not a typo. Its the question. Python gives me the expected error. But in `D`, no error. Why? – J Arun Mani Oct 25 '19 at 18:22
  • 1
    I think you've messed up your error messages a bit in `C` - I don't see why it would say "no attribute 'w'" when you assign to attribute `z`... – DavidW Oct 25 '19 at 18:23
  • 1
    Sorry, yes, I get what you're asking about `D` - it's just the error message for `C` isn't quite what I'd expect – DavidW Oct 25 '19 at 18:23
  • Ops. Sorry. That should be `c`. But the sense is same. – J Arun Mani Oct 25 '19 at 18:24
  • 1
    https://stackoverflow.com/questions/1816483/python-how-does-inheritance-of-slots-in-subclasses-actually-work – DavidW Oct 25 '19 at 18:24

1 Answers1

2

Your question is answered inside Usage of __slots__?

Requirements:
To have attributes named in __slots__ to actually be
stored in slots instead of a __dict__, a class must
inherit from object.

To prevent the creation of a __dict__, you must
inherit from object and all classes in the inheritance
must declare __slots__ and none of them can
have a '__dict__' entry.

In particular, you must have an unbroken chain of only __slots__ from the original object inheritance to your current class, or you will have a __dict__ available and the slots won't be able to prevent modification.

tl;dr: GObject.Object doesn't use slots, so you can't use a subclass of it to prevent setting attributes

Cireo
  • 4,197
  • 1
  • 19
  • 24