Created
December 17, 2019 14:14
-
-
Save vskrachkov/2163ae5c5e9f5320c4b455da04d87065 to your computer and use it in GitHub Desktop.
find subclasses and bases
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 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