ch17: update from book draft
This commit is contained in:
25
17-it-generator/tree/step2/test_tree.py
Normal file
25
17-it-generator/tree/step2/test_tree.py
Normal file
@@ -0,0 +1,25 @@
|
||||
from tree import tree
|
||||
|
||||
|
||||
def test_1_level():
|
||||
class One: pass
|
||||
expected = [('One', 0)]
|
||||
result = list(tree(One))
|
||||
assert expected == result
|
||||
|
||||
|
||||
def test_2_levels_4_leaves():
|
||||
class Branch: pass
|
||||
class Leaf1(Branch): pass
|
||||
class Leaf2(Branch): pass
|
||||
class Leaf3(Branch): pass
|
||||
class Leaf4(Branch): pass
|
||||
expected = [
|
||||
('Branch', 0),
|
||||
('Leaf1', 1),
|
||||
('Leaf2', 1),
|
||||
('Leaf3', 1),
|
||||
('Leaf4', 1),
|
||||
]
|
||||
result = list(tree(Branch))
|
||||
assert expected == result
|
||||
14
17-it-generator/tree/step2/tree.py
Normal file
14
17-it-generator/tree/step2/tree.py
Normal file
@@ -0,0 +1,14 @@
|
||||
def tree(cls):
|
||||
yield cls.__name__, 0
|
||||
yield from sub_tree(cls) # <1>
|
||||
|
||||
|
||||
def sub_tree(cls):
|
||||
for sub_cls in cls.__subclasses__():
|
||||
yield sub_cls.__name__, 1 # <2>
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
for cls_name, level in tree(BaseException):
|
||||
indent = ' ' * 4 * level
|
||||
print(f'{indent}{cls_name}')
|
||||
Reference in New Issue
Block a user