Skip to content

Commit 8dd2046

Browse files
committed
node.precedes(n) now works across trees and is used in mentionA < mentionB
1 parent a879b2d commit 8dd2046

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

udapi/core/coref.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ def __lt__(self, other):
3434
if node1 is node2:
3535
node1 = self._words[-1] if self._words else self._head
3636
node2 = other._words[-1] if other._words else other._head
37-
return node1 < node2
38-
return node1 < node2
37+
return node1.precedes(node2)
38+
return node1.precedes(node2)
3939

4040
@property
4141
def head(self):

udapi/core/node.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,12 @@ def ord(self, new_ord):
127127
self._ord = new_ord
128128

129129
def __lt__(self, other):
130+
"""Calling `nodeA < nodeB` is equivalent to `nodeA.ord < nodeB.ord`.
131+
132+
Note that this does not work as expected for nodes from different trees
133+
because `ord` is the word order within each sentence.
134+
For comparing the word order across trees, use `nodeA.precedes(nodeB)` instead.
135+
"""
130136
return self._ord < other._ord
131137

132138
@property
@@ -660,8 +666,18 @@ def next_node(self):
660666
return None
661667

662668
def precedes(self, node):
663-
"""Does this node precedes another `node` in word order (`self.ord < node.ord`)?"""
664-
return self._ord < node._ord
669+
"""Does this node precedes another `node` in word order?
670+
671+
This method handles correctly also nodes from different trees (but the same zone).
672+
If you have nodes from the same tree, it is faster and more elegant to use just `nodeA < nodeB`,
673+
which is equivalent to calling `nodeA.ord < nodeB.ord`.
674+
For sorting nodes from the same tree, you can use `nodes.sort()` or `sorted(nodes)`.
675+
"""
676+
if self._root is node._root:
677+
return self._ord < node._ord
678+
if self._root._zone != node._root._zone:
679+
raise ValueError(f"Cannot compare word order across zones: {self} {node}")
680+
return self._root._bundle.number < node._root._bundle.number
665681

666682
def is_leaf(self):
667683
"""Is this node a leaf, ie. a node without any children?"""

0 commit comments

Comments
 (0)