Skip to content

Instantly share code, notes, and snippets.

@spookylukey
Last active November 29, 2023 09:17
Show Gist options
  • Save spookylukey/3490772633e19c97b5cfd808b79d113a to your computer and use it in GitHub Desktop.
Save spookylukey/3490772633e19c97b5cfd808b79d113a to your computer and use it in GitHub Desktop.
get_all_subclasses utility
import itertools
flatten = itertools.chain.from_iterable
def get_all_subclasses(cls: type) -> set[type]:
"""
Return all subclasses of a class, recursively.
"""
# `type` and other metaclasses don't behave nicely with `__subclasses__`,
# we have to filter them out
if cls is type or type in cls.__bases__:
return []
level_1 = cls.__subclasses__()
return set(level_1).union(flatten(map(get_all_subclasses, level_1)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment