How to find all the subclasses of a class given its name?
⚡TLDR
Quickly unearth subclasses of 'MyClass'
:
- Obtain class object using
globals()
: - Outline direct children with
__subclasses__()
:
Dig deeper with recursion
To unmask all layers of subclasses, not just the direct children, you need to gather all generations:
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:
- Import the guests you know are coming
- Use
importlib
for the surprise guests:
__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:
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
Linked
Linked
Was this article helpful?