[BUG] `Text.right_crop(0)` empties the text and an amount larger than the text makes `len()` raise

オープン 初心者向け
#4,265 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

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

評価

難易度
2/5
見積もり時間
1〜3時間
初心者へのやさしさ
76/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
python
領域
backend

調査の方向性

まず Rich のソース内で Text.right_crop() を見つけ、issue の例とあわせて、span とキャッシュされた長さの更新処理を読みます。ゼロ、負の値、長さと同じ値、長さを超える値を対象とした既存のテストを確認し、示された期待動作に合わせてテストケースを追加または更新します。完了条件は、ゼロ以下の値ではテキストが変化せず、長さを超える値では len(text) == 0 となる空のテキストが生成されることです。

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

説明

Rich main (3a109cc), Python 3.13.

Text.right_crop() is documented as "Remove a number of characters from the end of the text", but amounts outside 1..len(text) leave the Text object inconsistent:

from rich.text import Text

def probe(amount):
    text = Text("abc")
    try:
        text.right_crop(amount)
        return repr(text.plain), len(text)
    except Exception as error:
        return type(error).__name__ + ": " + str(error)

for amount in (1, 0, -1, 3, 10):
    print(amount, probe(amount))
1  ('ab', 2)
0  ('', 3)
-1 ('a', 4)
3  ('', 0)
10 ValueError: __len__() should return >= 0

Two separate problems:

  1. amount == 0 wipes the text. max_offset = len(self.plain) - 0 keeps every span, but self._text = [self.plain[:-amount]] is self.plain[:0] == "", so the text becomes empty while _length stays at 3 and the spans still cover 0..3. Any code that crops by a computed amount can therefore lose the line instead of leaving it alone.
  2. amount > len(text) makes _length negative (3 - 10), so the next len(text) raises ValueError: __len__() should return >= 0.

(The negative-amount case, where right_crop(-1) leaves len(text) == 4, is #4256; the same clamp covers it.)

Expected: a non-positive amount is a no-op, and an amount larger than the text removes the whole text (plain == "", len(text) == 0), so the cached length and spans stay consistent.

Pull requests to this repository are restricted to collaborators, so I can't send the change directly. The fix is small:

def right_crop(self, amount: int = 1) -> None:
    """Remove a number of characters from the end of the text."""
    if amount <= 0:
        return
    amount = min(amount, len(self.plain))
    max_offset = len(self.plain) - amount
    ...

With that, the table above becomes 1 ('ab', 2), 0 ('abc', 3), -1 ('abc', 3), 3 ('', 0), 10 ('', 0).

主要言語
Python
スター
57.8k
フォーク
2.6k
平均マージ
20分
マージ済み PR(30日)
3

環境構築

はじめの一歩

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

Textualize/rich のほかの issue

Textualize/rich の issue をすべて見る

似ている issue

Python の issue をもっと見る

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

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