python / python/mypy

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

Open
#20,067 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-runtime-semantics
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the reported reproduction with Python 3.10 and mypy, including --python-version=3.10, and confirm the incorrect diagnostic. Trace the handling of the @classmethod and @property combination, then add or update coverage so the example type-checks without the error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.