This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author riccardomurri
Recipients riccardomurri
Date 2019-03-25.11:16:45
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1553512605.72.0.860422023516.issue36422@roundup.psfhosted.org>
In-reply-to
Content
The behavior of `tempfile.TemporaryDirectory()` is to delete the
temporary directory when done; this behavior cannot be turned off
(there's no `delete=False`like `NamedTemporaryFile` has instead).

However, in case a filesystem has been mounted on the temporary
directory, this can lead to the entire filesystem being removed.

While I agree that it would be responsibility of the programmer to
ensure that anything that has been mounted on the temp dir is
unmounted, the current behavior makes it quite easy to shoot oneself
in the foot.  Consider the following code::

    @contextmanager
    def mount_sshfs(localdir, remote):
        subprocess.run(f"sshfs {remote} {localdir}")
        yield
        subprocess.run(f"fusermount -u {localdir}", check=True)

    with TemporaryDirectory() as tmpdir:
         with mount_sshfs(tmpdir, remote):
              # ... do stuff ...

Now, even if the `fusermount` call fails, cleanup of
`TemporaryDirectory()` will be performed and the remote filesystem
will be erased!

Is there a way this pattern can be prevented or at least mitigated?
Two options that come to mind:

* add a `delete=True/False` option to `TemporaryDirectory` like `NamedTemporaryFile` already has
* add a `delete_on_error` option to avoid performing cleanup during error exit from a `with:` block

I have seen this happen with Py 3.6 but it's likely there in the entire 3.x series since `TemporaryDirectory` was added to stdlib.

Thanks,
Riccardo
History
Date User Action Args
2019-03-25 11:16:45riccardomurrisetrecipients: + riccardomurri
2019-03-25 11:16:45riccardomurrisetmessageid: <1553512605.72.0.860422023516.issue36422@roundup.psfhosted.org>
2019-03-25 11:16:45riccardomurrilinkissue36422 messages
2019-03-25 11:16:45riccardomurricreate