python / python/mypy

Meta issue: better `getattr` support

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

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

feature meta
主要言語
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.

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

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

はじめの一歩

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

調査の方向性

まず、issue で参照されている既存の checkmember ロジックを読み、関連する issue 1424 と 10409 を確認します。string と Literal の名前およびデフォルト値を含む、要求された getattr の例を比較し、示されている reveal_type の結果と missing-attribute エラーを完了条件として使用します。

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

評価

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

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

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