Meta issue: better `getattr` support
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
Feature
One thing that bothered me for a long time is getattr and its very broad return type even for simplest cases:
from typing import Literal
class Some:
def __init__(self) -> None:
self.a = 1
s = Some()
reveal_type(s.a) # Revealed type is "builtins.int"
reveal_type(getattr(s, 'a')) # Revealed type is "Any"
reveal_type(getattr(s, 'b')) # Revealed type is "Any"
reveal_type(getattr(s, 'a', None)) # Revealed type is "Union[Any, None]"
a: Literal['a']
reveal_type(getattr(s, a)) # Revealed type is "Any"
ab: Literal['a', 'b']
reveal_type(getattr(s, ab)) # Revealed type is "Any"
So, I propose to add better support for it to mypy.
The same example, after the support is added:
from typing import Literal
class Some:
def __init__(self) -> None:
self.a = 1
s = Some()
reveal_type(s.a) # Revealed type is "builtins.int"
reveal_type(getattr(s, 'a')) # Revealed type is "builtins.int"
reveal_type(getattr(s, 'b')) # error: "Some" has no attribute "b"
reveal_type(getattr(s, 'a', None)) # Revealed type is "builtins.int"
a: Literal['a']
reveal_type(getattr(s, a)) # Revealed type is "builtins.int"
ab: Literal['a', 'b']
reveal_type(getattr(s, ab)) # error: "Some" has no attribute "b"
reveal_type(getattr(s, ab, None)) # Revealed type is "builtins.int | None"
I have even written a custom plugin for it at some point.
Why?
This pattern is quite popular among Python developers. geattr(obj, 'string_key', None) is used for compatibility, optional dependencies, etc. That's something you can find in almost any project.
Technical details
I am going to utilize existing checkmember logic.
I even plan to support attribute plugins, where possible, because a.x and getattr(a, 'x') are semantically identical.
For now only str literals and Literal str types are going to be supported.
Related issues and problems
I am calling this issue "meta", because there are several very related problems I want to mention / solve here:
Next steps
I will start with a PR with a code prototype in a couple of days.
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、issue で参照されている既存の checkmember ロジックを読み、関連する issue 1424 と 10409 を確認します。string と Literal の名前およびデフォルト値を含む、要求された getattr の例を比較し、示されている reveal_type の結果と missing-attribute エラーを完了条件として使用します。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- 機能追加
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100