python / python/cpython

annotationlib.ForwardRef.__hash__ raises TypeError on an unhashable value

Open
#152,358 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib topic-typing type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at annotationlib.ForwardRef.hash and compare the handling of globals and cell with owner and extra_names. Review sibling issue #143831 and reproduce the failure shown here; done means equal forward references containing unhashable values can be hashed consistently without TypeError.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.