Вы можете использовать рекурсивный подход, например так:
import pygraphviz as pgv
class Test:
subgraph1 = 'foo'
subgraph2 = 'bar'
def __init__(self):
self.structure = []
self.G = pgv.AGraph(directed=True)
self.G.add_subgraph(label=self.subgraph1, name='cluster_' + self.subgraph1)
s1 = self.G.get_subgraph('cluster_' + self.subgraph1)
s1.add_subgraph(label=self.subgraph2, name='cluster_' + self.subgraph2)
s1.add_node('s1 node')
s2 = s1.get_subgraph('cluster_' + self.subgraph2)
s2.add_node('s2 node')
# ... other methods here ...
def get_structure(self, node_name, node=None):
if node is None:
node = self.G
for subgraph in node.subgraphs():
if node_name in subgraph.nodes():
self.structure.append(subgraph.node_attr['label'])
self.get_structure(node_name, subgraph)
def subgraph_structure_as_list(self, node_name):
self.structure = []
self.get_structure(node_name)
return self.structure
Вы можете использовать subgraph_structure_as_list
так, как хотите:
a = Test()
print(a.subgraph_structure_as_list('s2 node'))
print(a.subgraph_structure_as_list('s1 node'))
Вывод:
['foo', 'bar']
['foo']