Search code examples
pythoninheritanceslots

Get all __slots__ of derived class


I need to initialise all slots of an instance with None. How do I get all slots of a derived class?

Example (which does not work):

class A(object):
    __slots__ = "a"

    def __init__(self):
        # this does not work for inherited classes
        for slot in type(self).__slots__:
            setattr(self, slot, None)

class B(A):
    __slots__ = "b"

I could use an additional class attribute which holds the slots (including the inherited) for all classes, like

class A(object):
    __slots__ = "a"
    all_slots = "a"

    def __init__(self):
        # this does not work for inherited classes
        for slot in type(self).all_slots:
            setattr(self, slot, None)

class B(A):
    __slots__ = "b"
    all_slots = ["a", "b"]

but that seems suboptimal.

Any comments are appreciated!

Cheers,

Jan


Solution

  • First of all, it's

    class A(object):
        __slots__ = ('a',)
    class B(A):
        __slots__ =  ('b',)
    

    Making a list that contains all elements contained by __slots__ of B or any of its parent classes would be:

    from itertools import chain
    slots = chain.from_iterable(getattr(cls, '__slots__', []) for cls in B.__mro__)