Skip to content

Commit b4e615c

Browse files
committed
Added to_lol, eq and hash to Tree
1 parent 84aae2a commit b4e615c

File tree

2 files changed

+44
-4
lines changed

2 files changed

+44
-4
lines changed

src/liblet/display.py

+23-4
Original file line numberDiff line numberDiff line change
@@ -293,12 +293,24 @@ def _to_tree(ast_node):
293293

294294
return _to_tree(node)
295295

296+
def to_lol(self):
297+
def walk(T):
298+
return (T.root, *tuple(walk(child) for child in T.children))
299+
300+
return walk(self)
301+
296302
def __repr__(self):
297303
def walk(T):
298304
return '({}: {})'.format(T.root, ', '.join(map(walk, T.children))) if T.children else f'({T.root})'
299305

300306
return walk(self)
301307

308+
def __eq__(self, other):
309+
return isinstance(other, Tree) and self.to_lol() == other.to_lol()
310+
311+
def __hash__(self):
312+
return hash(self.to_lol())
313+
302314
def _gv_graph_(self):
303315
G = GVWrapper(
304316
dict( # noqa: C408
@@ -712,7 +724,8 @@ def _fmt(r, c):
712724
letstr(self.data[r], self.fmt['elem_sep'], sort=self.fmt['letstr_sort'], remove_outer=True),
713725
)
714726
for r in rows
715-
), True
727+
),
728+
True,
716729
)
717730

718731

@@ -735,7 +748,8 @@ def _repr_html_(self):
735748
)
736749
+ '</pre></td>'
737750
for l in range(N, L - 1, -1) # noqa: E741
738-
), True
751+
),
752+
True,
739753
)
740754

741755

@@ -777,8 +791,13 @@ def embed_css(custom_css=CUSTOM_CSS):
777791
return HTML(f'<style>{custom_css}</style>')
778792

779793

780-
def liblet_table(content, as_str = False):
781-
return f'<table class="liblet" data-quarto-disable-processing="true">{content}</table>' if as_str else HTML(f'<table class=liblet>{content}</table>')
794+
def liblet_table(content, as_str=False):
795+
return (
796+
f'<table class="liblet" data-quarto-disable-processing="true">{content}</table>'
797+
if as_str
798+
else HTML(f'<table class=liblet>{content}</table>')
799+
)
800+
782801

783802
def resized_svg_repr(obj, width=800, height=600):
784803
if hasattr(obj, '_repr_image_svg_xml'):

src/tests/display_test.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import unittest
2+
3+
from liblet.display import Tree
4+
5+
6+
class TestTree(unittest.TestCase):
7+
def test_from_lol(self):
8+
lol = (1, (11,), (12, (121,), (122,)))
9+
t = Tree.from_lol(lol)
10+
self.assertEqual(str(t), '(1: (11), (12: (121), (122)))')
11+
12+
def test_to_lol(self):
13+
lol = (1, (11,), (12, (121,), (122,)))
14+
t = Tree.from_lol(lol)
15+
self.assertEqual(t.to_lol(), lol)
16+
17+
def test_equals(self):
18+
lol = (1, (11,), (12, (121,), (122,)))
19+
t1 = Tree.from_lol(lol)
20+
t2 = Tree.from_lol(lol)
21+
self.assertEqual(t1, t2)

0 commit comments

Comments
 (0)