python / python/mypy

Subclass default overrides more general baseclass type hint

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

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

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

説明

Bug Report

When a base class field has a general type hint (eg: Union[int, str] or a base class) and a subclass sets a default without a type hint, the field's type hint is narrowed to the specific default value's type rather than maintaining the original base class's hint. This prevents a second-order subclass from setting a new default with a different type that would otherwise align with the originally specified hint on the first class.

This is particularly relevant when using something like dataclasses or pydantic.

To Reproduce

from typing import Union

class A:
    x: Union[int, str] = 5

class B(A):
    x = 5

class C(B):
    # error: Incompatible types in assignment (expression has type "str", base class "B" defined the type as "int")
    x = "5"

class RefA:
    x: A

class RefB(RefA):
    x = B()

class RefC(RefB):
    # error: Incompatible types in assignment (expression has type "A", base class "RefB" defined the type as "B")
    x = A()

Expected Behavior

The B.x and RefB.x fields to maintain their base classes type hint rather than implicitly narrow to the default value's type. Thus, C.x and RefC.x fields to support values matching the first base class's type hint.

Actual Behavior

The middle subclasses implicitly narrow the type hint to type(default_value) so a new default on a third subclass must match that, rather than the original explicit hint.

Your Environment

  • Mypy version used: 0.930
  • Mypy command-line flags: n/a
  • Mypy configuration options from mypy.ini (and other config files): n/a
  • Python version used: 3.9.7
  • Operating system and version: macos 12.0.1

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

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

はじめの一歩

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

調査の方向性

提供されている継承の例 A/B/C および RefA/RefB/RefC から始め、mypy がサブクラスの注釈なしの代入をどのように推論するかを追跡します。B.x と RefB.x が元の基底クラスのアノテーションを保持することを示す回帰テストを追加し、第 3 レベルの代入で報告されている非互換性エラーが発生しなくなったことを確認します。

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

評価

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

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

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