python / python/mypy

Problems with wrapper classes

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

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

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

説明

Let's say I have a Person class with a bunch of attributes; it comes from a library I don't control but for which type information exists. Now I have a PersonWrapper class which provides for defaults so that accessing missing attributes never raises an exception (think, use of instances in f-strings).

class PersonWrapper:
    def __init__(self, person: Person, default: Any = '') -> None:
        self.person = person
        self.default = default

    def __getattr__(self, attribute: str) -> Any:
        return getattr(self.person, attribute, self.default)

In general, any place I want to use a Person I might also want to use a PersonWrapper, so I have variables that can be assigned either a Person or a PersonWrapper. mypy seems not to be able to handle this, and I don't really know of any way to tell the type checker that it should treat Person and PersonWrapper as equivalent. For example, if I have this code:

def print_person(original_person: Person) -> None:
    person = PersonWrapper(original_person)
    # This attribute might be missing from the original person object.
    print(f'  Username: {person.username}')
    person = original_person
    # Only print this if the attribute exists.
    phone = getattr(person, 'phoneNumber', None)
    if phone:
        print(f'    Phone: {phone}')

mypy complains about the assignment of original_person to person:

error: Incompatible types in assignment (expression has type "Person", variable has type "PersonWrapper")

Because Person has some dynamic attribute access as well, I can't change the original assignment to:

    person: Person = cast(Person, PersonWrapper(original_person))

because then I get errors such as:

error: "Person" has no attribute "office"

The way I fix this is by changing the second assignment to use cast():

    person = cast(PersonWrapper, original_person)

This feels wrong, but maybe it's okay. What I think i'd like to do is to create an equivalence between PersonWrapper and Person, but then I'd probably still have to handle the dynamic parts of Person in some way. FWIW I didn't have much luck using Union[Person, PersonWrapper] either.

Is there a better way to handle wrapper classes?

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

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

はじめの一歩

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

調査の方向性

報告された Person/PersonWrapper の例と、代入推論、Union[Person, PersonWrapper]、cast()、動的な getattr の相互作用から始めます。mypy のソースファイルやテストは指定されていません。望ましい型付けの動作を定義し、実装箇所が特定できたら、焦点を絞った回帰テストを追加します。

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

評価

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

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

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