Skip to content

Commit

Permalink
grass.jupyter: Use weakref.finalize to manage TemporaryDirectory (#2206
Browse files Browse the repository at this point in the history
)

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.
  • Loading branch information
wenzeslaus committed Feb 14, 2022
1 parent e8ef996 commit 74aac0a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
11 changes: 10 additions & 1 deletion python/grass/jupyter/display.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import os
import shutil
import tempfile
import weakref

import grass.script as gs

Expand Down Expand Up @@ -94,7 +95,15 @@ def __init__(
# 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
Expand Down
12 changes: 11 additions & 1 deletion python/grass/jupyter/render3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import os
import tempfile
import weakref

import grass.script as gs

Expand Down Expand Up @@ -95,7 +96,16 @@ def __init__(
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:
Expand Down

0 comments on commit 74aac0a

Please sign in to comment.