From 899997d9312fce4cebcfa47e59ba13eaacc01448 Mon Sep 17 00:00:00 2001 From: Dongdong Tian Date: Mon, 6 May 2024 14:41:35 +0800 Subject: [PATCH] Track current PyGMT figure to avoid calling the `figure` module repeatly --- pygmt/_state.py | 9 +++++++++ pygmt/figure.py | 21 +++++++++++++++------ 2 files changed, 24 insertions(+), 6 deletions(-) create mode 100644 pygmt/_state.py diff --git a/pygmt/_state.py b/pygmt/_state.py new file mode 100644 index 00000000000..e7297a0253c --- /dev/null +++ b/pygmt/_state.py @@ -0,0 +1,9 @@ +""" +Private dictionary to keep tracking of current PyGMT state. + +The feature is only meant for internal use by PyGMT and is experimental! +""" + +_STATE = { + "current_figure": None, +} diff --git a/pygmt/figure.py b/pygmt/figure.py index ce8693a43f3..d798a4a27b7 100644 --- a/pygmt/figure.py +++ b/pygmt/figure.py @@ -7,6 +7,8 @@ from pathlib import Path from tempfile import TemporaryDirectory +from pygmt._state import _STATE + try: import IPython @@ -100,16 +102,23 @@ def _activate_figure(self): All plotting commands run afterward will append to this figure. - Unlike the command-line version (``gmt figure``), this method does not - trigger the generation of a figure file. An explicit call to - :meth:`pygmt.Figure.savefig` or :meth:`pygmt.Figure.psconvert` must be - made in order to get a file. + Unlike the command-line version (``gmt figure``), this method does not trigger + the generation of a figure file. An explicit call to + :meth:`pygmt.Figure.savefig` or :meth:`pygmt.Figure.psconvert` must be made in + order to get a file. """ - # Passing format '-' tells pygmt.end to not produce any files. - fmt = "-" + # Activate the figure only if it's not already activated + if _STATE["current_figure"] == self._name: + return + with Session() as lib: + # Passing format '-' tells pygmt.end to not produce any files. + fmt = "-" lib.call_module(module="figure", args=[self._name, fmt]) + # Track the current activated figure name + _STATE["current_figure"] = self._name + def _preprocess(self, **kwargs): """ Call the ``figure`` module before each plotting command to ensure we're plotting