Explain Codes LogoExplain Codes Logo

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

python
prompt-engineering
functions
recursion
Alex KataevbyAlex Kataev·Feb 17, 2025
TLDR
# Because who doesn't want to find their own descendants? Cls = globals()['MyClass'] # Change 'MyClass' to your class name # Gather them children! subclasses = Cls.__subclasses__()

Quickly unearth subclasses of 'MyClass':

  • Obtain class object using globals():
    Cls = globals()['MyClass']
  • Outline direct children with __subclasses__():
    subclasses = Cls.__subclasses__()

Dig deeper with recursion

To unmask all layers of subclasses, not just the direct children, you need to gather all generations:

def find_all_kids(cls): """Find all children, grandchildren, and so on for a class.""" for kiddo in cls.__subclasses__(): yield kiddo yield from find_all_kids(kiddo) # recursive magic # Use example all_kids = list(find_all_kids(Cls)) # It's a family reunion!

Import to find more kids

__subclasses__() only finds subclasses that have already been imported. To ensure you have a full house at the family reunion:

  1. Import the guests you know are coming
  2. Use importlib for the surprise guests:
    import importlib module = importlib.import_module('module_name') # Module your class might be chilling in Cls = getattr(module, 'MyClass') # The name of your class

__init_subclass__ for keeping tabs on the kids

__init_subclass__ lets you keep tabs on your descendants (in Python 3.6+). Every time a new subclass is created, it gets added to a list:

class Base: kids = [] # Where the kids go def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) Base.kids.append(cls) # Found a kid? Add it to the list!

Advanced hunting strategies

Up your game with these extra tricks:

  • Use a class method to tidy up the family gathering
  • Override __subclasses__ within __init_subclass__ for full control
  • Yield those kids like a seasoned farmer
  • Avoid eval like you avoid your creepy uncle. It's not safe!

Things to watch out for

Even family reunions can have hitches. Here's what to keep in mind:

  • Only classes in the current scope can join the fun
  • Keep in mind dynamic imports for those who didn't RSVP
  • Shy away from vars(), it might invite the whole neighborhood instead