diff --git a/src/sage/misc/temporary_file.py b/src/sage/misc/temporary_file.py index 998260be8eb..4e9ece019d2 100644 --- a/src/sage/misc/temporary_file.py +++ b/src/sage/misc/temporary_file.py @@ -32,7 +32,9 @@ # as the parent for all temporary files & directories created by them. # This lets us clean up after those two functions when sage exits normally # using an atexit hook -TMP_DIR_FILENAME_BASE = tempfile.TemporaryDirectory() +# Note that `TemporaryDirectory()` will cleanup on program exit; +# we keep the atexit hook to be redundant, in case that fails. +TMP_DIR_FILENAME_BASE = tempfile.TemporaryDirectory(prefix='sage_') atexit.register(lambda: TMP_DIR_FILENAME_BASE.cleanup()) @@ -533,14 +535,17 @@ def spyx_tmp() -> str: We cache the result of this function "by hand" so that the same temporary directory will always be returned. A function is used to delay creating a directory until (if) it is needed. The temporary - directory is removed when sage terminates by way of an atexit - hook. + directory is automatically removed when sage terminates. """ global _spyx_tmp if _spyx_tmp: return _spyx_tmp - d = tempfile.TemporaryDirectory() - _spyx_tmp = os.path.join(d.name, 'spyx') - atexit.register(lambda: d.cleanup()) + # We don't use `tempfile.TemporaryDirectory()` here because it + # is not clear when it will or will not be cleaned. Sometimes it + # might not be cleaned up at all, and starting in python 3.13 it + # might be cleaned up on child exit, breaking parallel testing. + # For some reason this doesn't affect the `TemporaryDirectory` + # stored in the global `TMP_DIR_FILENAME_BASE`. + _spyx_tmp = tmp_dir(name='spyx_') return _spyx_tmp