`str.translate` caching values causes incorrect result
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 36k
- 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 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
首先,使用提供的 Python 重現程式執行三個計數翻譯表案例,並比較它們的 getitem 呼叫次數和結果。接著找出 CPython 中 str.translate 的進入點和測試;當行為與文件化的契約一致,且有回歸測試涵蓋時,即表示完成。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- backend
- Issue 類型
- 缺陷
- 難度
- 4/5
- 預估耗時
- 3-5 天
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 45/100