Skip to content

pathlib.Path.rename() and replace() may move a file before rejecting a bytes target #156035

Description

@lpyu001

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytopic-pathlibtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions