Skip to content

Instantly share code, notes, and snippets.

@rmariano
Last active September 15, 2020 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmariano/7e0d778045db60fd3f31 to your computer and use it in GitHub Desktop.
Save rmariano/7e0d778045db60fd3f31 to your computer and use it in GitHub Desktop.
LeaveClasses.md
class Top(object):
pass
class A(Top): pass
class B(Top): pass
class A1(A): pass
class A2(A): pass
class B1(B): pass
class B2(B): pass
class get_leave_classes(object):
"""Iterator that yields a subclass on each iteration
Return only bottom-level classes, the leaves of the hierarchy tree
"""
def __init__(self, top_cls):
self.to_explore = top_cls.__subclasses__()
def __iter__(self):
return self
def __next__(self):
while self.to_explore:
leaf = self.to_explore.pop(0)
if not leaf.__subclasses__():
return leaf
self.to_explore.extend(leaf.__subclasses__())
raise StopIteration()
for class_ in get_leave_classes(Top):
print(class_.__name__)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment