python / python/mypy

"error: only instance methods can be decorated with @property" is incorrect for Python 3.9 and later

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

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

bug topic-runtime-semantics
主要言語
Python
スター
20.6k
フォーク
3.3k
平均マージ
1日 18時間
マージ済み PR(30日)
54

説明

Bug Report

The code shown in the "to reproduce" section works correctly in Python 3.10 and later (and would work correctly in 3.9 and later if it didn't use inspect.get_annotations), but triggers an unconditional error message from mypy: "Only instance methods can be decorated with @property".

As far as I can tell, that was true in 3.8 and earlier, but that restriction was relaxed as a new feature of 3.9. See the "Changed in 3.9" note at the end of https://docs.python.org/3.9/library/functions.html#classmethod, which specifically calls out @property as something that can now be wrapped in @classmethod.

This is closely related to, but not quite the same as, #2563.

To Reproduce

from inspect import get_annotations

class BugDemo:
    @classmethod
    @property
    def permitted_keys(cls) -> frozenset[str]:
        return frozenset(get_annotations(cls).keys())

    a: str
    b: int

if __name__ == "__main__":
    print(repr(BugDemo.permitted_keys))

playground: https://mypy-play.net/?mypy=latest&python=3.10&gist=91eef6c76933a64774b3ac310976da27

Expected Behavior

This program should be considered type-correct.

Actual Behavior

$ python3.10 bug.py
frozenset({'b', 'a'})

$ mypy bug.py
bug.py:4: error: Only instance methods can be decorated with @property  [misc]

$ mypy --python-version=3.10 bug.py
bug.py:4: error: Only instance methods can be decorated with @property  [misc]

Your Environment

  • Mypy version used: 1.18.2 (compiled: yes)
  • Mypy command-line flags: see "actual behavior" section
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.10

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

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

はじめの一歩

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

調査の方向性

まず、--python-version=3.10 を含めて Python 3.10 と mypy で報告された再現手順を実行し、誤った診断を確認します。@classmethod と @property の組み合わせの処理を追跡し、その後、例がエラーなしで型チェックされるようにカバレッジを追加または更新します。

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

評価

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

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

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