Browse Source

grass.jupyter: Use weakref.finalize to manage TemporaryDirectory (#2206)

Although tempfile.TemporaryDirectory uses weakref.finalize to delete the directory and its documentation does mention deletion during garbage-collection and during interpreter shutdown, the intention in its source code is that a with statement is used or explicit cleanup call is made because otherwise it generates a warning about implicit deletion. Pylint correctly generates warning suggesting with statement (consider-using-with).

In the future, we may consider implementing context-manager and cleanup method to the render classes, but even with that we need to stretch the existence of the temporary directory beyond one method, so the with statement is not applicable. For now, the classes are using only weakref.finalize which is sufficient for a notebook where the object life time is linked with the notebook's kernel life time which is relatively short. The Pylint warning is disabled and an explanatory comment is above.
Vaclav Petras 3 năm trước cách đây
mục cha
commit
74aac0a8f5
2 tập tin đã thay đổi với 21 bổ sung2 xóa
  1. 10 1
      python/grass/jupyter/display.py
  2. 11 1
      python/grass/jupyter/render3d.py

+ 10 - 1
python/grass/jupyter/display.py

@@ -16,6 +16,7 @@
 import os
 import shutil
 import tempfile
+import weakref
 
 import grass.script as gs
 
@@ -94,7 +95,15 @@ class GrassRenderer:
         # temporary directory that we can delete later. We need
         # this temporary directory for the legend anyways so we'll
         # make it now
-        self._tmpdir = tempfile.TemporaryDirectory()
+        # Resource managed by weakref.finalize.
+        self._tmpdir = (
+            tempfile.TemporaryDirectory()
+        )  # pylint: disable=consider-using-with
+
+        def cleanup(tmpdir):
+            tmpdir.cleanup()
+
+        weakref.finalize(self, cleanup, self._tmpdir)
 
         if filename:
             self._filename = filename

+ 11 - 1
python/grass/jupyter/render3d.py

@@ -15,6 +15,7 @@
 
 import os
 import tempfile
+import weakref
 
 import grass.script as gs
 
@@ -95,7 +96,16 @@ class Grass3dRenderer:
         self._resolution_fine = resolution_fine
 
         # Temporary dir and files
-        self._tmpdir = tempfile.TemporaryDirectory()
+        # Resource managed by weakref.finalize.
+        self._tmpdir = (
+            tempfile.TemporaryDirectory()
+        )  # pylint: disable=consider-using-with
+
+        def cleanup(tmpdir):
+            tmpdir.cleanup()
+
+        weakref.finalize(self, cleanup, self._tmpdir)
+
         if filename:
             self._filename = filename
         else: