`str.translate` caching values causes incorrect result
Chưa có ai nhận issue này.
- Ngôn ngữ chính
- Python
- Star
- 77.2k
- Fork
- 35.9k
- Chỉ số merge pull request
- Chỉ số pull request đang chờ
Mô tả
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
Hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Hướng nghiên cứu
Bắt đầu bằng cách chạy trình tái hiện Python được cung cấp với ba trường hợp bảng dịch có đếm, rồi so sánh số lần gọi getitem và kết quả của chúng. Sau đó, xác định điểm vào của CPython và các bài kiểm thử cho str.translate; công việc được xem là hoàn tất khi hành vi nhất quán với hợp đồng được ghi chép và được bao phủ bởi các bài kiểm thử hồi quy.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Đánh giá
- Công nghệ
- python
- Lĩnh vực
- backend
- Loại issue
- Lỗi
- Độ khó
- 4/5
- Thời gian dự kiến
- 3-5 ngày
- Mức độ hoạt động
- Đình trệ
- Độ rõ ràng
- Khá rõ ràng
- Mức phù hợp với người mới
- 45/100