| 1 |
# Copyright (c) 2018, Ansible Project |
| 2 |
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) |
| 3 |
""" |
| 4 |
Modules in _utils are waiting to find a better home. If you need to use them, be prepared for them |
| 5 |
to move to a different location in the future. |
| 6 |
""" |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
import inspect |
| 11 |
import typing as t |
| 12 |
|
| 13 |
_Type = t.TypeVar('_Type') |
| 14 |
|
| 15 |
|
| 16 |
def get_all_subclasses(cls: type[_Type], *, include_abstract: bool = True, consider_self: bool = False) -> set[type[_Type]]: |
| 17 |
"""Recursively find all subclasses of a given type, including abstract classes by default.""" |
| 18 |
subclasses: set[type[_Type]] = {cls} if consider_self else set() |
| 19 |
queue: list[type[_Type]] = [cls] |
| 20 |
|
| 21 |
while queue: |
| 22 |
parent = queue.pop() |
| 23 |
|
| 24 |
for child in parent.__subclasses__(): |
| 25 |
if child in subclasses: |
| 26 |
continue |
| 27 |
|
| 28 |
queue.append(child) |
| 29 |
subclasses.add(child) |
| 30 |
|
| 31 |
if not include_abstract: |
| 32 |
subclasses = {sc for sc in subclasses if not inspect.isabstract(sc)} |
| 33 |
|
| 34 |
return subclasses |