python / python/mypy

constrained TypeVar does not allow default of one of the constraint choices

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

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

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

説明

I suspect this is related to https://github.com/python/mypy/issues/3737 but seems to be a specific sub-case that should be unambigious (and pyright accepts the code unchanged)

Bug Report

a constrained TypeVar T: (U, V) "T must be either U or V" does not accept either U or V as a default value

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.12&gist=b7cc5486d300e5869277d59fa33a2b03

class U: pass
class V: pass

class C[T: (U, V)]:
    def __init__(self, tp: type[T] = U) -> None:
        self.x: dict[int, T] = {1: tp()}

(I kinda understand that mypy wouldn't know well enough that C() would actually be C[U] -- I've omitted overloads that make that work with mypy -- but the error on the default parameter still remains)

Expected Behavior

(no errors)

Actual Behavior

main.py:5: error: Incompatible default for argument "tp" (default has type "type[U]", argument has type "type[V]")  [assignment]
Found 1 error in 1 file (checked 1 source file)

I'm guessing that for a constrained typevar mypy is just checking each possible constraint against the default value?

Your Environment

  • Mypy version used: 1.12.1
  • Mypy command-line flags: n/a
  • Mypy configuration options from mypy.ini (and other config files): n/a
  • Python version used: 3.12.x

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

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

はじめの一歩

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

調査の方向性

リンク先の mypy-play ページにある制約付き TypeVar の例を mypy 1.12.1 で再現し、その後、デフォルト引数の型チェック経路を追跡してください。両方の制約の選択肢のデフォルト値をカバーする回帰テストを追加し、その例でエラーが報告されないことを確認してください。

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

評価

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

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

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