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
- Direct Descendants Only: The method only returns
immediate children. If
Dogis subclassed byGoldenRetriever,Animal.__subclasses__()will listDog, but notGoldenRetriever. 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)
)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.
Class-Level Execution: The method is meant to be called on the class itself, not on an instance of the class.
Common Use Cases
- Plugin Systems: Applications can define an abstract
base class or interface. Third-party extensions or add-ons subclass this
base, allowing the application to discover and load all active plugins
automatically using
BasePlugin.__subclasses__(). - Dynamic Factory Pattern: Instead of maintaining a manual dictionary mapping type names to classes, a base factory class can inspect its subclasses to locate the appropriate implementation based on an attribute or class name.
- Automated Testing and Validation: Test suites can use the method to verify that all subclasses of a base model implement required methods or configuration variables.
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.