Skip to content

The result of type(TypeVar) is not hashable #20409

@arnimarj

Description

@arnimarj

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions