[Python-Dev] Adding test.support.safe_rmpath()

eryk sun eryksun at gmail.com
Tue Feb 19 07:48:25 EST 2019

On 2/16/19, Richard Levasseur <richardlev at gmail.com> wrote:
> First: The tempfile module is a poor fit for testing (don't get me wrong,
> it works, but its not *nice for use in tests*)*.* This is because:
> 1. Using it as a context manager is distracting. The indentation signifies
> a conceptual scope the reader needs to be aware of, but in a test context,
> its usually not useful. At worst, it covers most of the test. At best, its
> constrained to a block at the start.
> 2. tempfile defaults to binary mode instead of text; just another thing to
> bite you.
> 3. On windows, you can't reopen the file, so for cross-platform stuff, you
> can't even use it for this case.

Python opens files with at least read and write sharing in Windows, so
typically there's no problem with opening a file multiple times. The
problem is with deleting and renaming open files. Typically delete
access is not shared, and, even if it is, a normal delete just sets a
disposition. A deleted file is unlinked only after all handles have
been closed. Similarly, replacing an open file via os.replace will
fail because it can't be unlinked.

In Windows 10 we can delete and rename files with POSIX-like
semantics. To do this, open a handle with delete access and call
SetFileInformationByHandle to set the FileDispositionInfoEx or
FileRenameInfoEx information. Thus far this is supported by NTFS, and
I think it's only NTFS. It's still not completely like POSIX, since it
requires delete-access sharing. But it does provide immediate
unlinking, which avoids the race condition when trying to remove a
directory that has watched files. Programs that have open files that
have been unlinked can continue to access them normally.

More information about the Python-Dev mailing list