__hash__ method in str child class causing unintended side effects
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 77.2k
- Fork
- 36k
- Merge medio
- 1g 9h
- PR unite (30g)
- 558
Descrizione
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
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Non sono identificati né un file sorgente né un test. Inizia riproducendo l'esempio su CPython 3.10.5 e analizza l'interazione tra hash e str della sottoclasse personalizzata di str; il lavoro sarebbe completo dopo aver confermato se il comportamento è involontario e aver identificato un test di regressione o una modifica di portata limitata.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- backend
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Da chiarire
- Idoneità per principianti
- 22/100