Bug report
Bug description:
pathlib.Path.rename() and Path.replace() can successfully move a file and then raise TypeError when the target is a bytes path, or an os.PathLike object whose __fspath__() method returns bytes.
The important issue is not whether pathlib should support bytes paths. Pathlib deliberately requires string paths. The problem is that target validation takes place only after the filesystem has already been modified. A caller that sees the exception may reasonably assume that the rename or replacement failed,even though the source no longer exists and the destination now contains the file.
Reproducer
import os
import tempfile
from pathlib import Path
for method_name in ("rename", "replace"):
with tempfile.TemporaryDirectory() as directory:
source = Path(directory, "source")
target = Path(directory, "target")
source.write_text("payload")
try:
getattr(source, method_name)(os.fsencode(target))
except Exception as error:
print(method_name, type(error).__name__, str(error))
print("source exists:", source.exists())
print("target exists:", target.exists())
print("target contents:", target.read_text())
result:
rename TypeError argument should be a str or an os.PathLike object where __fspath__ returns a str, not 'bytes'
source exists: False
target exists: True
target contents: payload
replace TypeError argument should be a str or an os.PathLike object where __fspath__ returns a str, not 'bytes'
source exists: False
target exists: True
target contents: payload
CPython versions tested on:
CPython main branch
Operating systems tested on:
Linux
Linked PRs
Bug report
Bug description:
pathlib.Path.rename()andPath.replace()can successfully move a file and then raiseTypeErrorwhen the target is a bytes path, or anos.PathLikeobject whose__fspath__()method returns bytes.The important issue is not whether pathlib should support bytes paths. Pathlib deliberately requires string paths. The problem is that target validation takes place only after the filesystem has already been modified. A caller that sees the exception may reasonably assume that the rename or replacement failed,even though the source no longer exists and the destination now contains the file.
Reproducer
result:
CPython versions tested on:
CPython main branch
Operating systems tested on:
Linux
Linked PRs