python / python/cpython

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

オープン
#156,035 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

stdlib topic-pathlib type-bug
主要言語
Python
スター
77.2k
フォーク
36k
PR マージ指標
PR 指標を取得中

説明

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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、提供された reproducer を実行し、次に pathlib.Path.rename() と Path.replace() を見つけて、それらのターゲットがいつ検証されるかを追跡します。完了の条件は、どちらかの操作がソースまたはデスティネーションの状態を変更する前に bytes のターゲットが拒否され、両方のメソッドがカバレッジに含まれていることです。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
operating-systems
issue の種類
バグ
難易度
3/5
見積もり時間
1〜2日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。