python / python/mypy

The result of `type(TypeVar)` is not hashable

オープン
#20,409 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

bug
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

提供された例を使って mypy 1.19.0 で報告を再現し、mypy --strict foo.py を実行してください。汎用の type[_T] 引数が Hashable に対してどのようにチェックされるかを追跡し、受け入れられている具体的な type[str] のケースを維持しながら、報告された呼び出しのカバレッジを追加してください。完了条件は、汎用の呼び出しでエラーが発生しないことです。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
devtools
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
38/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。