Python subclasses() Method Explained

The __subclasses__() method in Python is a built-in class method that returns a list of all immediate subclasses currently loaded in memory that inherit from a given base class. This introspection feature enables developers to inspect inheritance hierarchies at runtime, making it a powerful tool for building plugin architectures, implementing dynamic factory patterns, and automating class registration without hardcoded registries.

How __subclasses__() Works

Every class in Python inherits from the root object type, which defines the __subclasses__() method. When invoked on a class, it queries Python's internal inheritance tree and returns a list containing references to its direct derived classes.

class Animal:
    pass

class Dog(Animal):
    pass

class Cat(Animal):
    pass

print(Animal.__subclasses__())
# Output: [<class '__main__.Dog'>, <class '__main__.Cat'>]

Key Behaviors and Characteristics

  1. Direct Descendants Only: The method only returns immediate children. If Dog is subclassed by GoldenRetriever, Animal.__subclasses__() will list Dog, but not GoldenRetriever. To access all descendants in a deeply nested hierarchy, you must traverse the tree recursively.
def get_all_subclasses(cls):
    subclasses = set(cls.__subclasses__())
    return subclasses.union(
        s for c in subclasses for s in get_all_subclasses(c)
    )
  1. In-Memory Tracking: Python tracks subclasses via weak references. A class will only appear in the list if the module defining it has already been imported into the current runtime environment. Unimported files will not appear.

  2. Class-Level Execution: The method is meant to be called on the class itself, not on an instance of the class.

Common Use Cases

Limitations

Because __subclasses__() relies on imported modules, it cannot find subclasses dynamically from the filesystem without an import mechanism loading them first. Additionally, because subclasses can be dynamically created or garbage-collected during execution, the returned list reflects only the state of the program at the exact moment the method is called.