Assignability to a Protocol Using `Self` Must Respect Variance
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 1.8k
- フォーク
- 302
- 平均マージ
- 23時間
- マージ済み PR(30日)
- 8
説明
I just stumbled across this paragraph:
If I understand it correctly, then the following code is fine, i.e., Foo is assignable to Proto according to the explanation:
from __future__ import annotations
from typing import Protocol, Self
class Proto(Protocol):
def f(self, x: Self) -> None: ...
class Foo:
def f(self, x: Sub) -> None:
pass
class Sub(Foo):
pass
x: Proto = Foo()
However, type checkers like mypy and pyright reject this code. This aligns with my expectation: If I have an instance x: Proto, then I should be able to call x.f(x). But for y: Foo, I cannot call y.f(y).
The paragraph in question should distinguish between covariant, contravariant, and invariant occurences of Self:
from __future__ import annotations
from typing import Protocol, Self
class Proto(Protocol):
def f(self, x: Self) -> None: ... # contravariant
def g(self, x: Self) -> Self: ... # x: contravariant, return type: covariant
def h(self, x: list[Self]) -> None: ... # invariant
class Sup:
pass
class Foo(Sup):
def f(self, x: Sup) -> None: # x can be of type Foo or any superclass
pass
def g(self, x: Sup) -> Sub: # return type can be Foo or any subclass
raise RuntimeError()
def h(self, x: list[Foo]) -> None: # no sub-/superclass allowed as argument to list
pass
class Sub(Foo):
pass
x: Proto = Foo() # OK, also according to mypy and pyright
I assume that all the uses of Self are valid in this example, at least mypy and pyright do not complain and I couldn’t find any statement that would restrict Self in protocols to covariant positions or even return types only. Maybe it also makes sense to adjust the example after the paragraph in question. Currently, it only uses Self in a return type.
コントリビューションガイド
このリポジトリのコントリビューションガイドは索引されていません
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
リンクされた2540-2544行の docs/spec/generics.rst から始め、protocols における Self についての周辺の議論を確認してください。提供された例を mypy と pyright で実行し、その後、Self の反変、共変、不変の使い方を説明するように段落と近くの例を更新してください。完了の条件は、仕様がチェッカーで実証された動作と一致することです。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- documentation
- issue の種類
- ドキュメント
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 38/100