New submission from Riccardo Murri <riccardo.mu...@gmail.com>:

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

----------
components: Library (Lib)
messages: 338795
nosy: riccardomurri
priority: normal
severity: normal
status: open
title: tempfile.TemporaryDirectory() removes entire directory tree even if it's 
a mount-point
type: behavior
versions: Python 3.6

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue36422>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to