Skip to content

Instantly share code, notes, and snippets.

@vskrachkov
Created December 17, 2019 14:14
Show Gist options
  • Save vskrachkov/2163ae5c5e9f5320c4b455da04d87065 to your computer and use it in GitHub Desktop.
Save vskrachkov/2163ae5c5e9f5320c4b455da04d87065 to your computer and use it in GitHub Desktop.
find subclasses and bases
import inspect
from typing import List, TypeVar, Type, Set
T = TypeVar('T')
def find_subclasses(cls: Type[T], deep=True) -> List[Type[T]]:
res: List[Type[T]] = []
subclasses: List[Type[T]] = cls.__subclasses__()
for subclass in subclasses:
if not inspect.isabstract(subclass):
res.append(subclass)
if deep:
sub_res = find_subclasses(subclass, deep=deep)
res = res + sub_res
return res
def find_bases(cls: Type[T]) -> Set[Type[T]]:
res: Set[Type[T]] = set(cls.__mro__)
res.remove(cls)
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment