Referring to class attributes of a generic type
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
I apologize for posting my question here as an issue; I am doing this out of desperation since my original post on StackOverflow went unanswered for three weeks. Below is a near-verbatim copy from StackOverflow.
I have an abstract base class which defines several class attributes which are types themselves (i.e., nested types); the attributes are overridden in concrete derived classes inheriting from the abstract class. The concrete derived classes are used with several other classes which are type-annotated as generics, where the type parameter has a type constraint that it must be derived from the abstract class. I want these other classes (generics) to refer to the class attributes (nested types) of the concrete classes. The following example should demonstrate the idea:
import typing
class Base:
A: typing.Type[Base]
class One(Base):
class A(Base): # overrides Base.A
pass
class Two(Base):
class A(One): # overrides Base.A
pass
T = typing.TypeVar('T', bound=Base)
class Foo(typing.Generic[T]): # the generic
def foo(self, a: typing.Type[T.A]) -> T: # <-- here, see T.A
...
f: Foo[Two] = Foo()
f.foo(Two.A) # line 22 is here
MyPy v0.701 reports an error on line 22:
Argument 1 to "foo" of "Foo" has incompatible type "Type[A]"; expected "Type[Two]"
MyPy seems to ignore the attribute reference at T.A. How do I make it understand that I am trying to refer to the type available via the attribute .A? The attribute is guaranteed to be available because the type variable T is constrained to Base, which has A. Note that extending the set of generic types is not an option; I could elaborate on this but the explanation would be too specific to my application.
UPDATE: MyPy v0.711 with --new-semantic-analyzer yields a more comprehensible error message:
Name 'T.A' is not defined
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
この issue にはリポジトリのファイルやテストが記載されていないため、最小限の Python 例から始め、mypy が TypeVar の境界、ジェネリックアノテーション、クラス属性の型参照をどのように処理するかを追跡してください。要求された型付けの動作について、実装または制限が定義され、回帰テストでカバーされていれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- compilers
- issue の種類
- 機能追加
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 停滞
- 明瞭さ
- 説明が足りない
- 初心者へのやさしさ
- 25/100