python / python/mypy

Incorrect type narrowing when unpacking union of tuple on an existing variable

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

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

bug priority-0-high topic-type-narrowing
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

Bug Report

When unpacking a tuple with Union types over existing variables, some of the types disappear.

To Reproduce

import random


def foo() -> tuple[int, None] | tuple[int, str]:
    if random.choice((True, False)):
        return 0, None
    return 5, "thing"


res = None

status, res = foo()
reveal_type(res)  # builtins.str

Expected Behavior

res should be an Optional[str], not a str.

Actual Behavior

The Optional gets lost in the assignment.

Your Environment

  • Mypy version used: 0.950
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.10
  • Operating system and version: Manjaro Linux x86_64 5.15.41-1-MANJARO

This may be related to #9731, but I'm not sure about it.

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

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

はじめの一歩

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

調査の方向性

Issue にはリポジトリのファイルもテストも記載されていません。まず、提供された再現プログラムを Python 3.10 上の mypy 0.950 で実行し、関連する issue #9731 を確認してください。タプルアンパックによる代入と型の絞り込みを追跡し、reveal_type(res) が str ではなく Optional[str] を報告したときに補完が表示されることを確認してください。

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

評価

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

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

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