python / python/mypy

Field of union needs to be different type when reading vs setting

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

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

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

説明

Bug Report

Mypy appears to infer that the type of a field of a variable that is typed as a union is a single type whether that field is being read or updated. The type correct when reading the field (union of the types of the fields) , but not correct when setting as it does not enforce that the value being assigned needs to be valid for both of the types in the union (intersection of the types of the fields).

To Reproduce

class Foo:
    a: int

class Bar:
    a: str

either: Foo | Bar
either.a = 1  # No error, despite not being valid for Bar

More detailed example: https://mypy-play.net/?mypy=latest&python=3.12&gist=bf74f1ba35979f10b1878b2e1abca865

Expected Behavior

Mypy should report the assignment as an error if it does not work with all the types in the union.

Actual Behavior

No error, despite the assignment allowing a field of type str to be an int

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

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

はじめの一歩

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

調査の方向性

まず、提供された Foo/Bar の例とリンクされた mypy-play の再現コードを実行し、union に対するフィールドの読み取りと代入を比較します。関連する union 属性代入のチェックを追跡し、すべての union メンバーに対して有効な場合にのみ代入が受け入れられるようにすると問題が解決し、報告された例でエラーが発生することを確認します。

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

評価

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

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

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