How to find all the subclasses of a class given its name with Python?

Estimated read time 2 min read

To find all the subclasses of a class given its name in Python, you can utilize the inspect module from the Python standard library. Here’s an example:

import inspect

def find_subclasses(class_name):
    subclasses = []
    for name, obj in inspect.getmembers(class_name):
        if inspect.isclass(obj) and issubclass(obj, class_name):
    return subclasses

# Test the function
class MyBaseClass:

class SubClass1(MyBaseClass):

class SubClass2(MyBaseClass):

class SubSubClass(SubClass1):

subclasses = find_subclasses(MyBaseClass)
print("Subclasses of MyBaseClass are:", subclasses)

In this example, we define a function called find_subclasses that takes the class name as an argument. Inside the function, we initialize an empty list called subclasses to store the subclasses.

We use the inspect.getmembers() function to retrieve all the members of the given class name. The getmembers() function returns a list of tuples, where each tuple contains the name and object of a member.

We then iterate over each member using a loop. For each member, we check if it is a class (using inspect.isclass(obj)) and if it is a subclass of the given class name (using issubclass(obj, class_name)). If both conditions are true, we add the class object to the subclasses list.

Finally, we return the subclasses list.

You can test the function by passing the name of your base class to the find_subclasses function, and it will return a list of all the subclasses of that class. In the example, we define several classes (MyBaseClass, SubClass1, SubClass2, and SubSubClass) and use find_subclasses(MyBaseClass) to find the subclasses of MyBaseClass. The function will print the list of subclasses.

Note that the find_subclasses function expects the name of the class itself as a parameter, not a string representation of the class name.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply