python / python/typing

Proposal: inheritance + annotations

オープン
#269 コメント 21 件 リアクション 42 件 担当者 0 名 GitHub で見る

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

topic: feature
主要言語
Python
スター
1.8k
フォーク
302
平均マージ
23時間
マージ済み PR(30日)
8

説明

After some time annotating non-trivial codebases, I've found something that feels like a nuisance and a bad practice. Essentially, when overriding methods in subclasses, having to re-specify the whole type signatures in subclasses is:

  • type consuming (I'm writing/annotating a subclass and have to copy potentially complicated types for a lot of parameters)
  • error prone
  • not a source new information (which is the benefit of annotations)
  • a violation of the DRY principle (if I choose to change the type of an argument in the superclass, I have to edit all the subclasses).

One cases where this trivially happens is when defining standard python magic methods; I want my __str__ methods checked, but it feels silly to tell the typechecker every time that "yes, this method returns a string". It also happens in more complicated definitions, for example https://github.com/dmoisset/django/blob/typing-requests/django/core/files/uploadhandler.py#L83 and https://github.com/dmoisset/django/blob/typing-requests/django/core/files/uploadhandler.py#L83 vs line 170 of the same file.

Currently, the PEP says «For a checked function, the default annotation for arguments and for the return type is Any». I'd like to introduce some exception to this rule for methods inheriting an annotated method.

I know that there's a potential problem with this that is when inheriting standard classes (especially but not limited to object) which already have annotated clases, may force undesired annotations. My idea here is to introduce some kind of marker (perhaps a @typing.inherit_type_hints decorator?) that can be used at class and method levels and means "inherit annotations from the parent class unless specifically overriden by this class". In this way it's opt-in and also tells both the human reader and the static analyzer where to lookup the annotations.

The implementation of this decorator could be trivial (another identity decorator, just used as a marker for static analysis tools) , but also could actually copy the __anotations__ field to make the inherited information also available to runtime tools.

What do you think of this?

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

このリポジトリのコントリビューションガイドは索引されていません

はじめの一歩

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

調査の方向性

まず提案と参照されている django/core/files/uploadhandler.py の例を確認し、その後、オプトインの inherit_type_hints マーカーがオーバーライドされたメソッドや標準クラスとどのように相互作用するかを検討します。完了とするには、アノテーションが実行時に利用可能かどうかを含む、合意された継承モデルが必要であり、実装のスケッチだけでは不十分です。

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

評価

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

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

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