Skip to content

Commit 41529d3

Browse files
committed
Added child to Tree
1 parent 458dcc0 commit 41529d3

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/liblet/display.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,21 @@ def _to_tree(ast_node):
303303

304304
return _to_tree(node)
305305

306+
@property
307+
def child(self):
308+
"""Returns the only child of the tree, or raises an exception.
309+
310+
Returns:
311+
The first child of the tree.
312+
Raises:
313+
ValueError: if the tree has no children or more than one child.
314+
"""
315+
if len(self.children) == 1:
316+
return self.children[0]
317+
if len(self.children) == 0:
318+
raise ValueError('No children available')
319+
raise ValueError('More than one child present')
320+
306321
def to_lol(self):
307322
def walk(T):
308323
return (T.root, *tuple(walk(child) for child in T.children))

src/tests/display_test.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,18 @@
44

55

66
class TestTree(unittest.TestCase):
7+
def test_child(self):
8+
t = Tree('root', ['child'])
9+
self.assertEqual(t.child, 'child')
10+
11+
def test_two_children_raises_value_error(self):
12+
with self.assertRaises(ValueError):
13+
_ = Tree('root', ['child1', 'child2']).child
14+
15+
def test_no_children_raises_value_error(self):
16+
with self.assertRaises(ValueError):
17+
_ = Tree('root').child
18+
719
def test_from_lol(self):
820
lol = (1, (11,), (12, (121,), (122,)))
921
t = Tree.from_lol(lol)

0 commit comments

Comments
 (0)