Skip to content

Instantly share code, notes, and snippets.

@xflr6
Last active October 12, 2025 10:09
Show Gist options
  • Select an option

  • Save xflr6/cc0463a3e2fbad6f0d92 to your computer and use it in GitHub Desktop.

Select an option

Save xflr6/cc0463a3e2fbad6f0d92 to your computer and use it in GitHub Desktop.
Find all subclasses of a given class
"""Find all subclasses of a class with queue or stack."""
import collections
from collections.abc import Collection, Iterator
def itersubclasses(parent: type, /, *,
proper: bool = True,
exclude: Collection[type] = (type,)) -> Iterator[type]:
"""Yield `parent` subclasses recursively in breadth-first order."""
queue = collections.deque(parent.__subclasses__() if proper else [parent])
seen = set(exclude)
while queue:
if (cls := queue.popleft()) not in seen:
seen.add(cls)
yield cls
queue.extend(cls.__subclasses__())
print(itersubclasses.__doc__)
for cls in itersubclasses(object):
print(cls)
def itersubclasses(parent: type, /, *,
proper: bool = True,
exclude: Collection[type] = (type,)) -> Iterator[type]:
"""Yield `parent` subclasses recursively in depth-first order."""
stack = parent.__subclasses__()[::-1] if proper else [parent]
seen = set(exclude)
while stack:
if (cls := stack.pop()) not in seen:
seen.add(cls)
yield cls
stack.extend(reversed(cls.__subclasses__()))
print('', itersubclasses.__doc__, sep='\n')
for cls in itersubclasses(object):
print(cls)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment