Search code examples
pythonslots

How to gather all __slots__ for a class


Consider the following code:

class A(object):
    __slots__ = "a", "b"

    def __init__(self, a, b):
        self.a = a
        self.b = b

class B(A):
    __slots__ = "c",

    def __init__(self, a, b, c):
        super(B, self).__init__(a, b)
        self.c = c

b = B(1, 2, 3)
print(b.__slots__) # Prints just "('c',)", but I want to get ("a", "b", "c")

For a B class instance, I want to have access to all the slots declared in all its parents. Is it possible at all?


Solution

  • class A(object):
        __slots__ = "a", "b"
    
        def __init__(self, a, b):
            self.a = a
            self.b = b
    
    
    class B(A):
        __slots__ = "c",
    
        def __init__(self, a, b, c):
            super(B, self).__init__(a, b)
            self.c = c
    
    
    b = B(1, 2, 3)
    
    
    def all_slots(obj):
        slots = set()
        for cls in obj.__class__.__mro__:
            slots.update(getattr(cls, '__slots__', []))
        return slots
    
    
    print(all_slots(b))