python / python/mypy

Better error message for incompatible type assignment when using Generics

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

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

diagnostics needs discussion priority-1-normal
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

  • Are you reporting a bug, or opening a feature request?

Feature Request

  • Please insert below the code you are checking with mypy.
from typing import Generic, TypeVar


T = TypeVar("T", int, float)


class Foo(Generic[T]):
    def __init__(self, val: T):
        self.data: T = val 


def bar(x: T) -> Foo[T]:
    return Foo(x)


x = bar(1)
x = bar(2.0) # error thrown by mypy
  • What is the actual behavior/output?
    mypy throws this error:
error: Argument 1 to "bar" has incompatible type "float"; expected "int"
  • What is the behavior/output you expect?

This error message is thrown because of the combination of assigning a different type to x and using Generic. The error message is unclear because it indicates a type error on the argument passed to bar and can be interpreted as bar not accepting arguments of type float.

Having a different error message that mentions "Incompatible types in assignment" would be clearer.
A message to make it clearer that expression has type Foo[float], variable has type Foo[int]

  • What are the versions of mypy and Python you are using?

mypy 0.770 and Python 3.7.6

  • What are the mypy flags you are using? (For example --strict-optional)

None

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

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

はじめの一歩

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

調査の方向性

まず、mypy 0.770 と Python 3.7.6 で Generic の例を再現し、Foo[int] から Foo[float] への代入に焦点を当てます。bar の呼び出しと x への代入に対して生成される診断を追跡します。メッセージが、bar が float 引数を拒否していることを示唆するのではなく、互換性のない変数型と式の型を明確に特定すれば完了です。

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

評価

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

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

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