python / python/cpython

__hash__ method in str child class causing unintended side effects

オープン
#100,313 コメント 8 件 リアクション 0 件 担当者 0 名 GitHub で見る

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

interpreter-core type-bug
主要言語
Python
スター
77.2k
フォーク
36k
平均マージ
1日 9時間
マージ済み PR(30日)
558

説明

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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

ソースファイルもテストも特定されていません。まず CPython 3.10.5 で例を再現し、カスタム str サブクラスの hashstr の相互作用を調査してください。完了条件は、その挙動が意図しないものかどうかを確認し、範囲を限定した回帰テストまたは変更を特定することです。

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

評価

技術スタック
python
領域
backend
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
22/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。