python / python/mypy

Incorrect constraint inference for unions with nested generics

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

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

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

説明

🐛 Bug Report

From my search, it looks like an issue similar to #6417, but happening to unions of generic and nested generic.
mypy has troubles with inferring a proper constraint and passing a nested generic to function that should accept such nested generic fails.
The issue can be worked around with @overloads.

To Reproduce

Minimum reproduction:

from typing import List, TypeVar, Union

_T = TypeVar("_T")


def func(param: Union[List[_T], List[List[_T]]]) -> _T:
    ...

func([1])
func([[1]])

A more real-live example of where this is an issue is tornado's gen function (overloads there are the part of workaround for this issue):
https://github.com/tornadoweb/tornado/pull/2909/files

Expected Behavior

No errors.

Actual Behavior

main.py:10: error: Argument 1 to "func" has incompatible type "List[List[int]]"; expected "Union[List[<nothing>], List[List[<nothing>]]]"

Your Environment

  • Mypy version used: 0.781
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.8.5
  • Operating system and version: Windows 10

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

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

はじめの一歩

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

調査の方向性

main.py で最小限の再現から始め、mypy で func([1]) と func([[1]]) の動作が異なることを確認してください。Union[List[_T], List[List[_T]]] の制約推論の経路を追跡し、関連する issue #6417 およびリンクされている Tornado の pull request にある overload の回避策と比較してください。両方の呼び出しがエラーなしで型チェックを通れば完了です。

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

評価

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

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

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