`Style` keeps the ANSI codes from the first color system it renders with

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

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

評価

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

調査の方向性

バグは rich/style.py の Style._make_ansi_codes() にあり、この関数は色システムを記録せずに結果を Style._ansi にキャッシュします。また Style.parse は共有のキャッシュ済みインスタンスを返します。issue の再現スニペットを truecolor、standard、256 の各色システムで異なる順序で実行し、誤ったコードが出ることを確認してください。各コンソールが自身の色システム用のコードを受け取り、異なる色システムを持つ2つのコンソールで同じスタイルを描画するテストが用意されていれば完了です。

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

説明

Hi! I hit this while writing tests that render the same markup through consoles with different color systems.

Style._make_ansi_codes() caches its result in Style._ansi, but the cache doesn't record which color system the codes were made for. Since Style.parse is cached too, every console that parses the same style string shares one Style instance, so whichever console renders it first decides the codes for all the others.

import io
from rich.console import Console

def show(color_system):
    console = Console(file=io.StringIO(), color_system=color_system, force_terminal=True)
    console.print("[#ff8800]orange[/]", end="")
    print(f"{color_system:>9}: {console.file.getvalue()!r}")

show("truecolor")
show("standard")
show("256")

Output on Rich 15.0.0 (and main at 3a109cc):

truecolor: '\x1b[38;2;255;136;0morange\x1b[0m'
 standard: '\x1b[38;2;255;136;0morange\x1b[0m'
      256: '\x1b[38;2;255;136;0morange\x1b[0m'

The standard and 256-color consoles get truecolor codes. The other way round, a truecolor console that renders after a standard one gets \x1b[91m:

 standard: '\x1b[91morange\x1b[0m'
truecolor: '\x1b[91morange\x1b[0m'

I expected each console to get codes for its own color system:

truecolor: '\x1b[38;2;255;136;0morange\x1b[0m'
 standard: '\x1b[91morange\x1b[0m'
      256: '\x1b[38;5;208morange\x1b[0m'

It shows up in practice when a program has more than one console (say, one for the terminal and one recording to a file with a different color system), or in tests that create consoles with different settings in one process.

I have a small fix that stores the color system next to the cached codes, and I'm happy to open a PR.

Python 3.13, macOS.

主要言語
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 を短くまとめたダイジェスト。