Last active
November 29, 2023 09:17
-
-
Save spookylukey/3490772633e19c97b5cfd808b79d113a to your computer and use it in GitHub Desktop.
get_all_subclasses utility
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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