python / python/typing

Special-casing `__hash__`

Open
#2,284 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic: typing spec
Dominant language
Python
Stars
1.8k
Forks
302
Avg merge
23h
Merged PRs (30d)
8

Description

The concept of "hashable" and "unhashable" classes has been a bit of the sore point in the past. typeshed uses __hash__: ClassVar[None] to mark classes as non-hashable, although that requires a # type: ignore[assignment] annotation. I think this is special-cased by at least some type checkers for marking classes as unhashable.

Except for some wordage in the dataclasses section, the typing spec is silent about hashability. Since I believe that this needs special-casing by type checkers, it should be added to the typing spec. A raw idea:

  • Classes are hashable by default (due to object.__hash__() being implemented and typeshed having a type corresponding type annotation.)
  • To mark a class as non-hashable, use __hash__: ClassVar[None]. We could alternatively use something simpler such as __hash__ = None. I believe we used to use that, but I don't know why it's changed.
  • To mark a class as hashable, use def __hash__(self, ...) -> ..., usually def __hash__(self) -> int: ....
  • Sub-classes inherit their parent's hashability, unless overridden.

Contributor guide

No contributing guide indexed for this repository

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 by reading the typing spec, especially the existing dataclasses section, and review the discussion and proposed alternatives in this issue. Define the agreed rules for default hashability, __hash__: ClassVar[None] or __hash__ = None, explicit __hash__ methods, and inheritance; done means the typing spec documents the accepted behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
documentation
Issue type
Documentation
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.