`pathlib.Path.rename()` and `replace()` may move a file before rejecting a bytes target
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
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
- gh-156036
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the supplied reproducer, then locate pathlib.Path.rename() and Path.replace() and trace when their target is validated. Done means bytes targets are rejected before either operation changes the source or destination state, with coverage for both methods.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- operating-systems
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100