__hash__ method in str child class causing unintended side effects
還沒有人認領這個 Issue。
評估
研究方向
未指定原始碼檔案或測試。先在 CPython 3.10.5 上重現此範例,並調查自訂 str 子類別的 hash 與 str 之間的互動;完成條件是確認該行為是否非預期,並找出一個範圍狹窄的回歸測試或變更。
由索引模型根據 Issue 內容生成。
描述
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
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 36k
- 平均合併
- 1 天 9 小時
- 30 天內合併 PR
- 558
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
python/cpython 的其他 Issue
-
docs pending
難度 2/5 1-3 小時 新手友好度 78/100
-
stdlib type-feature
難度 2/5 1-3 小時 新手友好度 78/100
-
stdlib type-feature
難度 2/5 1-3 小時 新手友好度 72/100
-
build type-bug
難度 2/5 1-3 小時 新手友好度 76/100
-
stdlib topic-email type-feature
難度 2/5 1-3 小時 新手友好度 70/100
相似的 Issue
-
bug
難度 2/5 1-3 小時 新手友好度 86/100
zostera/django-bootstrap4#894 ·
-
難度 2/5 1-3 小時 新手友好度 78/100
use-agent-os/agent-os#3276 ·
-
難度 2/5 1-3 小時 新手友好度 88/100
zephyrproject-rtos/zephyr#119726 ·
-
area/auth bug comp/agent P3 platform/discord type/security
難度 2/5 1-3 小時 新手友好度 88/100
NousResearch/hermes-agent#117848 ·
-
難度 2/5 1-3 小時 新手友好度 82/100
zilliztech/memsearch#759 ·