__hash__ method in str child class causing unintended side effects

Aperta
#100,313 8 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
22/100
Tipo di issue
Bug
Chiarezza
Da chiarire
Stato di attività
Ferma
Stack tecnologico
python
Ambito
backend

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.

Descrizione

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
Lingua principale
Python
Stelle
77.2k
Fork
36k
Merge medio
1g 9h
PR unite (30g)
558

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di python/cpython

Tutte le issue di python/cpython

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.