python / python/mypy

Class inheriting from property doesn't typecheck properly when used as a decorator

オープン
#6,158 コメント 4 件 リアクション 0 件 担当者 0 名 GitHub で見る

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

bug false-positive priority-1-normal topic-descriptors
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

I have a custom class inheriting from property. When I go to use this as a decorator though mypy seems to miss that it's a property at all. This is with Python 3.6.3 and mypy 0.650.

Example:

class CustomProperty(property):
    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        super().__init__(fget, fset, fdel, doc)

class A:
    def __init__(self) -> None:
        self._val = 1

    @CustomProperty
    def val(self) -> int:
        return self._val

    @val.setter
    def val(self, v: int) -> None:
        self._val = v


def test_a() -> None:
    print(A.val)

Running mypy on this gives the following output:
mypy minimal2.py

minimal.py:14: error: Name 'val' already defined on line 10
minimal.py:14: error: Name 'val' is not defined
minimal.py:20: error: "Type[A]" has no attribute "val"

Contrast this with the same code with the builtin property which typechecks fine:

class B:
    def __init__(self) -> None:
        self._val = 1

    @property
    def val(self) -> int:
        return self._val

    @val.setter
    def val(self, v: int) -> None:
        self._val = v

def test_b() -> None:
    print(B.val)

It's possible that this is related to #1529 where @ilevkivskyi suggested that:

The original example now passes mypy, not sure however how useful the subclass can be (property is heavily special-cased in mypy), but at least the original bug is fixed, so closing this.

Is subclassing property frowned upon (or just not supported in mypy?).

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

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

はじめの一歩

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

調査の方向性

Python 3.6.3 と mypy 0.650 を使って minimal.py の例で報告を再現し、CustomProperty デコレータの場合と builtin property の場合を比較します。mypy による property サブクラスとデコレータ setter の処理を追跡します。完了の条件は、報告された duplicate-name または missing-attribute エラーなしに、カスタムクラスが builtin property と同じように型チェックされることです。

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

評価

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

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

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