python / python/cpython

annotationlib.ForwardRef.__hash__ raises TypeError on an unhashable value

Abierto
#152,358 4 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

stdlib topic-typing type-bug
Lenguaje dominante
Python
Estrellas
77.2k
Forks
35.9k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

annotationlib.ForwardRef defines both __eq__ and __hash__, but __hash__
raises TypeError when the forward reference holds an unhashable value, even
though two such forward references compare equal. This violates the data model
(objects that compare equal must be hashable and hash equal) and breaks storing
forward references in sets or as dict keys, which typing tools do.

Reproducer

from annotationlib import Format, get_annotations

class Unhashable:
    __hash__ = None

obj = Unhashable()

def f(a: undefined | obj): ...

fr1 = get_annotations(f, format=Format.FORWARDREF)["a"]
fr2 = get_annotations(f, format=Format.FORWARDREF)["a"]
assert fr1 == fr2
hash(fr1)   # TypeError: unhashable type: 'Unhashable'

obj resolves as a global, so the FORWARDREF format stores it in the forward
reference's __extra_names__. The same happens when the forward reference's
__owner__ is unhashable, for example a class whose metaclass sets
__hash__ = None.

Root cause

ForwardRef.__hash__ already hashes the unhashable __globals__ and __cell__
fields by identity (id()), but __owner__ and __extra_names__ are hashed
directly. __extra_names__ holds arbitrary values embedded in an annotation
that the FORWARDREF format could not render as a plain name, so those values
may be unhashable.

Regression

This is a sibling of #143831, which fixed the same class of bug for __cell__.
The traceback in that report already pointed at the __extra_names__ line.

Affected versions

3.14+ (where annotationlib was added).

Linked PRs
  • gh-152360

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza en annotationlib.ForwardRef.hash y compara el tratamiento de globals y cell con owner y extra_names. Revisa el issue relacionado #143831 y reproduce el fallo mostrado aquí; se considera terminado cuando las forward references iguales que contienen valores no hashables se pueden hashear de forma coherente sin TypeError.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
tooling
Tipo de issue
Error
Dificultad
2/5
Tiempo estimado
1-3 horas
Estado de actividad
Estancado
Claridad
Bien especificado
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.