Skip to content

Commit e0d2295

Browse files
committed
Adds the ability to concatenate independently created cursors.
1 parent ea00ac5 commit e0d2295

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

bonobo/structs/graphs.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,17 +29,26 @@ def __init__(self, graph, *, first=None, last=None):
2929
def __rshift__(self, other):
3030
""" Self >> Other """
3131

32+
# Allow to concatenate cursors.
33+
if isinstance(other, GraphCursor):
34+
chain = self.graph.add_chain(_input=self.last, _output=other.first)
35+
return GraphCursor(chain.graph, first=self.first, last=other.last)
36+
37+
# If we get a partial graph, or anything with a node list, use that.
3238
nodes = other.nodes if hasattr(other, "nodes") else [other]
3339

40+
# Sometimes, we use ellipsis to show "pseudo-code". This is ok, but can't be executed.
3441
if ... in nodes:
3542
raise NotImplementedError(
3643
"Expected something looking like a node, but got an Ellipsis (...). Did you forget to complete the graph?"
3744
)
3845

46+
# If there are nodes to add, create a new cursor after the chain is added to the graph.
3947
if len(nodes):
4048
chain = self.graph.add_chain(*nodes, _input=self.last, use_existing_nodes=True)
4149
return GraphCursor(chain.graph, first=self.first, last=chain.output)
4250

51+
# If we add nothing, then nothing changed.
4352
return self
4453

4554
def __enter__(self):
@@ -49,7 +58,10 @@ def __exit__(self, exc_type, exc_val, exc_tb):
4958
return None
5059

5160
def __eq__(self, other):
52-
return self.graph == other.graph and self.first == other.first and self.last == other.last
61+
try:
62+
return self.graph == other.graph and self.first == other.first and self.last == other.last
63+
except AttributeError:
64+
return False
5365

5466

5567
class PartialGraph:

tests/structs/test_graphs_new_syntax.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,3 +158,15 @@ def test_using_same_cursor_many_times_for_fork():
158158
assert g.outputs_of(c) == set()
159159
assert g.outputs_of(d) == set()
160160
assert g.outputs_of(e) == set()
161+
162+
163+
def test_concat_branches():
164+
a, b, c, d = get_pseudo_nodes(4)
165+
g = Graph()
166+
167+
c0 = g.orphan() >> a >> b
168+
c1 = g >> c >> d
169+
c2 = c1 >> c0
170+
171+
assert c2.first == BEGIN
172+
assert c2.last == g.index_of(b)

0 commit comments

Comments
 (0)