From a9eb4f64815196b209f74cf31eb5bed678a10292 Mon Sep 17 00:00:00 2001 From: Daniel Rojas Date: Fri, 15 Oct 2021 16:37:09 +0200 Subject: [PATCH] Create cache of graph to avoid generating it more than once --- src/wireviz/Harness.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/wireviz/Harness.py b/src/wireviz/Harness.py index 3a4cde8..31f0675 100644 --- a/src/wireviz/Harness.py +++ b/src/wireviz/Harness.py @@ -97,6 +97,7 @@ class Harness: if to_name in self.connectors: self.connectors[to_name].activate_pin(to_pin, Side.LEFT) + def create_graph(self) -> Graph: dot = Graph() dot.body.append(f'// Graph generated by {APP_NAME} {__version__}\n') @@ -446,10 +447,20 @@ class Harness: return dot + # cache for the GraphViz Graph object + # do not access directly, use self.graph instead + _graph = None + + @property + def graph(self): + if not self._graph: # no cached graph exists, generate one + self._graph = self.create_graph() + return self._graph # return cached graph + @property def png(self): from io import BytesIO - graph = self.create_graph() + graph = self.graph data = BytesIO() data.write(graph.pipe(format='png')) data.seek(0) @@ -458,7 +469,7 @@ class Harness: @property def svg(self): from io import BytesIO - graph = self.create_graph() + graph = self.graph data = BytesIO() data.write(graph.pipe(format='svg')) data.seek(0) @@ -466,7 +477,7 @@ class Harness: def output(self, filename: (str, Path), view: bool = False, cleanup: bool = True, fmt: tuple = ('html','png','svg','tsv')) -> None: # graphical output - graph = self.create_graph() + graph = self.graph svg_already_exists = Path(f'{filename}.svg').exists() # if SVG already exists, do not delete later # graphical output for f in fmt: