The result of `type(TypeVar)` is not hashable
Open
Nobody has claimed this yet.
bug
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
It seems that x: type[_T] is not hashable, and neither is y: _T = ... type(y).
To Reproduce
import functools
from typing import TypeVar
_T = TypeVar('_T')
@functools.lru_cache(maxsize=2048)
def do_something_expensive_with_type[_T](t_type: type[_T]) -> list[_T]:
return []
def MyFunc1[_T](t: _T, tt: type[_T]) -> list[_T]:
# arg-type - Argument 1 to "__call__" of "_lru_cache_wrapper" has incompatible type "type[_T]"; expected "Hashable"
do_something_expensive_with_type(type(t))
# arg-type - Argument 1 to "__call__" of "_lru_cache_wrapper" has incompatible type "type[_T]"; expected "Hashable"
do_something_expensive_with_type(tt)
# but type(t)/tt is indeed hashable
reveal_type(type(t).__hash__)
reveal_type(tt.__hash__)
return []
@functools.lru_cache(maxsize=2048)
def do_something_expensive_with_str(t_type: type[str]) -> list[str]:
return []
def MyFunc2() -> list[str]:
do_something_expensive_with_str(type(''))
reveal_type(str.__hash__)
return []
Expected Behavior
I'd expect the following not to give any errors for mypy --strict example.py
Actual Behavior
foo.py:15: error: Argument 1 to "__call__" of "_lru_cache_wrapper" has incompatible type "type[_T]"; expected "Hashable" [arg-type]
foo.py:18: error: Argument 1 to "__call__" of "_lru_cache_wrapper" has incompatible type "type[_T]"; expected "Hashable" [arg-type]
foo.py:21: note: Revealed type is "def (self: builtins.object) -> builtins.int"
foo.py:22: note: Revealed type is "def (self: builtins.object) -> builtins.int"
foo.py:35: note: Revealed type is "def (self: builtins.str) -> builtins.int"
Your Environment
Tested on mypy 1.19.0 (compiled: yes), like so: mypy --strict foo.py
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the report with mypy 1.19.0 using the provided example and run mypy --strict foo.py. Trace how generic type[_T] arguments are checked against Hashable, then add coverage for the reported calls while preserving the accepted concrete type[str] case; done means the generic calls produce no errors.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100