python / python/mypy

Wrong type hint after unpacking/swapping

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

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

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

説明

Bug Report

Unpacking a tuple in the below scenario results in wrong assumed types.

To Reproduce


import typing as t

def spam(val: t.Union[t.Type, None] = None) -> None:

  def eggs(type_: t.Type) -> None:
    pass

  reveal_type(val)
  if isinstance(val, type):
    reveal_type(val)
    val, foo = None, val
    reveal_type(val)
    reveal_type(foo)
    return eggs(foo)

Expected Behavior

After the line val, foo = None, val, I would expect that

  1. val has type None (ok)
  2. foo has type Type[Any]
  3. the call to eggs() passes

Actual Behavior

$ mypy test.py 
test.py:9: note: Revealed type is 'Union[Type[Any], None]'
test.py:11: note: Revealed type is 'Type[Any]'
test.py:13: note: Revealed type is 'None'
test.py:14: note: Revealed type is 'None'
test.py:15: error: Argument 1 to "eggs" has incompatible type "None"; expected "Type[Any]"
Found 1 error in 1 file (checked 1 source file)

This does not match with my expectations 2 and 3.

Your Environment

Python 3.9
Mypy 0.790
MacOS 10.14.6

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

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

はじめの一歩

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

調査の方向性

まず、報告された Python の例を mypy で実行し、val, foo = None, val の前後で表示される型を比較します。タプルのアンパックと型が絞り込まれた変数を、type-checker がどのように扱うかを調査します。fooType[Any] のままで、eggs(foo) の呼び出しがエラーなしで通れば完了です。

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

評価

技術スタック
python
領域
devtools
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
35/100

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

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