python / python/mypy

Allow Final attributes declared in class body if initialized in ctor

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

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

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

説明

There is currently a safety check around TypeVar-dependent Final attributes declared in the class body that I believe we can loosen when the variable is assigned in the ctor. This should work analogously to non-TypeVar-dependent final attributes declared in the class body, which also require an assignment in the ctor (otherwise they emit "Final name must be initialized with a value").

  • Are you reporting a bug, or opening a feature request? feature request
  • Please insert below the code you are checking with mypy,
    or a mock-up repro if the source is private. We would appreciate
    if you try to simplify your case to a minimal repro.
    from typing import Final, Generic, TypeVar
    
    
    WidgetT = TypeVar('WidgetT', bound='Widget')
    
    
    class Widget:
        pass
    
    
    class WidgetHolder(Generic[WidgetT]):
    
        widget: Final[WidgetT]
    
        def __init__(self, widget: WidgetT) -> None:
            self.widget = widget
    
  • What is the actual behavior/output?
    final.py: note: In class "WidgetHolder":
    final.py:13:5: error: Final name declared in class body cannot depend on type variables  [misc]
            widget: Final[WidgetT]
            ^
    

In case anyone comes across this issue, the workaround is currently to not declare in the class body, but declare in the ctor with self.widget: Final[WidgetT] = widget instead. But just because a workaround exists doesn't mean we shouldn't try to fix this.

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

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

はじめの一歩

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

調査の方向性

まず、提供された final.py の再現コードに対して mypy を実行し、クラス本体で宣言された Final 属性に対する既存のチェックを調べ、TypeVar に依存しない Final 属性の場合と比較します。属性が init で代入される場合に再現コードが型チェックを通過し、そこで初期化されない宣言については既存のエラーが残る状態になれば完了です。

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

評価

技術スタック
python
領域
devtools
issue の種類
機能追加
難易度
3/5
見積もり時間
1〜2日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
38/100

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

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