python / python/cpython

annotationlib.ForwardRef.__hash__ raises TypeError on an unhashable value

Aberta
#152,358 4 comentários 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

stdlib topic-typing type-bug
Linguagem predominante
Python
Estrelas
77.2k
Forks
36k
Métricas de merge de PRs
Métricas de PR pendentes

Descrição

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

Guia de contribuição

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Direção de pesquisa

Comece em annotationlib.ForwardRef.hash e compare o tratamento de globals e cell com owner e extra_names. Analise a issue relacionada #143831 e reproduza a falha mostrada aqui; considera-se concluído quando forward references iguais contendo valores não hashable puderem ser hasheadas de forma consistente sem TypeError.

Escrita pelo modelo de indexação a partir do texto da issue.

Avaliação

Stack de tecnologia
python
Domínio
tooling
Tipo de issue
Bug
Dificuldade
2/5
Tempo estimado
1-3 horas
Status de atividade
Estagnada
Clareza
Claramente especificada
Facilidade para iniciantes
35/100

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.