__hash__ method in str child class causing unintended side effects

Đang mở
#100,313 8 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

Đánh giá

Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức phù hợp với người mới
22/100
Loại issue
Lỗi
Độ rõ ràng
Cần làm rõ
Mức độ hoạt động
Đình trệ
Công nghệ
python
Lĩnh vực
backend

Hướng nghiên cứu

Chưa xác định được tệp nguồn hoặc bài kiểm thử nào. Hãy bắt đầu bằng cách tái hiện ví dụ trên CPython 3.10.5 và điều tra tương tác giữa hashstr của lớp con str tùy chỉnh; công việc được xem là hoàn tất khi xác nhận liệu hành vi này có ngoài ý muốn hay không và xác định được một regression test hoặc thay đổi có phạm vi hẹp.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

interpreter-core type-bug

Bug report

Consider the following example:

class MyStr(str):
    def __init__(self, value, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.value = value

    def __hash__(self) -> int:
        return hash(str(self))

    def __str__(self) -> str:
        return str(self.value)

def dummy_func(x):
    class MyClass:
        def __init__(self, data):
            self.data = data
        def __str__(self):
            return self.data
    str(MyClass(x))

dummy_func is a function that should have absolutely no side effects.
However, checkout:

a = MyStr("teststring")
a in {}
# False
dummy_func(a)
a in {}
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
#   File "<stdin>", line 6, in __hash__
#   File "<stdin>", line 6, in __hash__
#   File "<stdin>", line 8, in __str__
#   File "<stdin>", line 8, in __str__
#   File "<stdin>", line 8, in __str__
#   [Previous line repeated 329 more times]
# RecursionError: maximum recursion depth exceeded while calling a Python object
assert id(a.value.data) == id(a)

In this case, dummy_func mutates the input, and creates a weird circular dependency (i.e. id(a.value.data) == id(a)).

The issue can be fixed by removing the __hash__ method of MyStr.

Please confirm the behavior is unintended.

Environment

  • CPython versions tested on: Python 3.10.5
  • Operating system and architecture: CentOS, x86_64
Ngôn ngữ chính
Python
Star
77.2k
Fork
36k
Merge trung bình
1 ngày 9 giờ
Pull request đã merge (30 ngày)
558

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. 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.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của python/cpython

Tất cả issue của python/cpython

Issue tương tự

Thêm issue về Python

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.