Listing all instance of a class
Question: I wrote a Python module, with several classes that inherit from a single class
called `MasterBlock`. I want to import this module in a script, create several
instances of these classes, and then get a list of all the existing instances
of all the childrens of this `MasterBlock` class. I found some solutions with
`vars()['Blocks.MasterBlock'].__subclasses__()` but as the instances I have
are child of child of `MasterBlock`, it doesn't work.

Here is some example code:

Module:

    
    
    Class MasterBlock:
        def main(self):
            pass
    Class RandomA(MasterBlock):
        def __init__(self):
            pass
        # inherit the main function
    Class AnotherRandom(MasterBlock):
        def __init__(self):
            pass
        # inherit the main function
    

Script:

    
    
    import module
    a=module.RandomA()
    b=module.AnotherRandom()
    c=module.AnotherRandom()
    # here I need to get list_of_instances=[a,b,c]
    

Th ultimate goal is to be able to do:

    
    
    for instance in list_of_instances:
        instance.main()
    


Answer: What about adding a class variable, that contains all the instances of
`MasterBlock`? You can record them with:

    
    
    Class MasterBlock(object):
    
        all_instances = []  # All instances of MasterBlock
    
        def __init__(self,…):
            …
            self.all_instances.append(self)  # Not added if an exception is raised before
    

You get all the instances of `MasterBlock` with `MasterBlock.all_instances`
(or `instance.all_instances`).

This works if all base classes call the `__init__` of the master class (either
implicitly through inheritance or explicitly through the usual `super()`
call).

