python / python/mypy

How should we annotate cooperative inheritance?

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

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

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

説明

Consider annotating this example of cooperative multiple inheritance:

from typing import Any


class Hidden:

    def __init__(self, z: float, **kwargs: Any):
        super().__init__(**kwargs)
        self.z = z


class Base:

    def __init__(self, x: int, **kwargs: Any):
        super().__init__(**kwargs)
        self.x = x


class Inherited(Base):

    def __init__(self, y: int, **kwargs: Any):
        super().__init__(**kwargs)
        self.y = y


class Final(Inherited, Hidden):
    pass

MyPy gives errors because of the super-calls, which is addressed by https://github.com/python/mypy/issues/4001.

It would be nice for Inherited to ensure in its super-call that x has the right type, which is the topic of https://github.com/python/mypy/issues/4441 although it would also be nice for Final's constructor to only accept x, y, and z. I can't find any issue for that.

This example is done with __init__, but the problem can occur in any such “augmenting” method pattern. It is not restricted to __init__. This augmenting pattern always needs a top level method in some class. In __init__'s case, it's in object.

One idea is to have a special annotation on **kwargs, for example, typing.Collector? MyPy could then figure out the necessary arguments and their types in all derived classes. An inherited class would only be allowed to explicitly forward variables accepted by parents, but they should be able to forward anything. MyPy would make a best effort to ensure that all required arguments get in somehow.

I recognize that not everyone is a fan of cooperative MI, but I personally think it's quite beautiful. I would love to see MyPy handle it elegantly.

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

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

はじめの一歩

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

調査の方向性

まず、協調的な多重継承の例と、リンクされている mypy の issue 4001 および 4441 を読んでください。この作業では、メソッドの拡張に関するアノテーションと型チェックの動作について合意する必要があり、Final が受け入れるコンストラクター引数も含まれます。完了したことは、その例に対する mypy のチェックで実証する必要があります。

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

評価

技術スタック
python
領域
compilers, devtools
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
25/100

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

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