python / python/mypy

"Cannot determine type" if first assignment to attribute is unreachable

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

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

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

説明

To Reproduce

Run mypy on the following code:

class C:
    def __init__(self, a: str) -> None:
        if a is None:
            self.x = 123
        else:
            self.x = 456

It will output:

testcase.py:6: error: Cannot determine type of 'x'

Line 6 contains the second assignment to self.x.

Expected Behavior

mypy should be able to determine that the type of C.x is int.

Actual Behavior

The fact that a is annotated as str means that mypy determines that a is None is never true and therefore the first assignment to self.x is unreachable. The problem disappears if a is annotated as Optional[str].

So it looks like mypy half-ignores the first assignment to self.x: it doesn't use the type information available there since the code is unreachable, but it still considers it the assignment that determines the type of self.x.

Your Environment

mypy 0.790 with default configuration, running on Python 3.8.5 on openSUSE Linux.

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

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

はじめの一歩

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

調査の方向性

提供された Python リプロデューサーから始め、制御フローがその分岐を到達不能としてマークしたときの最初の属性代入について、mypy の型推論を追跡してください。例に対して mypy を再実行して修正を確認してください: C.x はエラーなしで int と推論され、Optional[str] のケースは引き続き機能するはずです。

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

評価

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

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

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