Base class type incorrectly overwritten by assignment in extending class
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
Bug Report
Defining a variable with a type union or optional, etc. and then setting the variable in an extending class overwrites the type of the variable to the narrower type used in the assignment. E.g. int | str to int. If the class is extended again, the type of the variable is the narrower type and can't be broadened again by a simple assignment or changed to another type compatible with the original base class.
To Reproduce
The following code results in an incompatible types in assignment error in the Eggs class:
class Spam:
var: int | str
class Ham(Spam):
var = 10
class Eggs(Ham):
var = "abc"
Expected Behavior
I would expect the explicitly set type of the base class Spam to be inherited by the first extending class Ham and that an assignment doesn't change the general type of the variable. So that the second extending class can still set var to a str.
Just like the following code is valid:
var: str | int
var = 10
var = "abc"
Actual Behavior
The assignment in Ham sets the type of var to int and the class Eggs can't set var to "abc" of type str.
mypy output:
a.py:8: error: Incompatible types in assignment (expression has type "str", base class "Ham" defined the type as "int") [assignment]
Your Environment
- Mypy version used:
mypy 1.10.0 (compiled: yes) - Python version used:
Python 3.12.3 (main, Apr 23 2024, 09:16:07) [GCC 13.2.1 20240417] on linux
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
mypy 1.10.0 を使用して3クラスのスニペットを再現し、Ham と Eggs での代入全体において、Spam で明示的にアノテーションされた union がどのように扱われるかを調べます。Ham の代入によって継承された型が狭められず、Eggs が incompatible-types エラーなしで文字列の代入を受け入れれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- tooling
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 45/100