`str.translate` caching values causes incorrect result
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 77.2k
- フォーク
- 35.9k
- PR マージ指標
- PR 指標を取得中
説明
Bug report
Bug description:
It seems that str.translate is caching values internally and this is causing unintended results.
When the translation table returns an ordinal or a string ordinal string, it caches the values returned by __getitem__ and will not call the function again. However if you are returning a 2-length string this doesn't occur (and in fact calls __getitem__ an additional time for some reason?).
I expect that the __getitem__ be executed for every character since the function documentation does not mention this caching value and more-so the function behaves inconsistently.
This is likely caused by #65317.
class counting_translate_ord(dict[int, int]):
def __init__(self) -> None:
super().__init__()
self.missing_calls = 0
def __getitem__(self, key: int) -> int:
self.missing_calls += 1
return ord(str(self.missing_calls % 10))
table = counting_translate_ord()
print(("----").translate(table)) # 1111
print(table.missing_calls) # 1
print(("!@#$").translate(table)) # 2345
print(table.missing_calls) # 5
class counting_translate_str(dict[int, str]):
def __init__(self) -> None:
super().__init__()
self.missing_calls = 0
def __getitem__(self, key: int) -> str:
self.missing_calls += 1
return str(self.missing_calls % 10)
table = counting_translate_str()
print(("----").translate(table)) # 1111
print(table.missing_calls) # 1
print(("!@#$").translate(table)) # 2345
print(table.missing_calls) # 5
class counting_translate_2str(dict[int, str]):
def __init__(self) -> None:
super().__init__()
self.missing_calls = 0
def __getitem__(self, key: int) -> str:
self.missing_calls += 1
return format(self.missing_calls, "02d")[:2]
table = counting_translate_2str()
print(("----").translate(table)) # 02030405
print(table.missing_calls) # 5
print(("!@#$").translate(table)) # 07080910
print(table.missing_calls) # 10
CPython versions tested on:
3.12
Operating systems tested on:
Linux
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、提供された Python 再現プログラムを 3 つのカウント付き変換テーブルのケースに対して実行し、それぞれの getitem 呼び出し回数と結果を比較します。次に、str.translate の CPython のエントリポイントとテストを特定します。動作が文書化された契約と一致し、回帰テストでカバーされていれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- backend
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 45/100