Skip to content

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

@zackw

Description

@zackw

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-runtime-semanticsmypy doesn't model runtime semantics correctly

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions