python / python/mypy

Reject invalid override of a property with a declared attribute

Open
#14,413 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Mypy doesn't complain about this, even though it fails at runtime with an exception:

class B:
    @property
    def x(self) -> int:
        return 0

class C(B):
    x: int
    def __init__(self) -> None:
        self.x = 4

C()

Exception:

Traceback (most recent call last):
  File "/Users/jukka/src/mypy/t/t5.py", line 11, in <module>
    C()
  File "/Users/jukka/src/mypy/t/t5.py", line 9, in __init__
    self.x = 4
    ^^^^^^
AttributeError: property 'x' of 'C' object has no setter

This doesn't generate an exception at runtime, however (and mypy correctly accepts this):

class B:
    @property
    def x(self) -> int:
        return 0

class C(B):
    x: int = 4

C()

Also, this already generates an error from mypy, as expected:

class B:
    @property
    def x(self) -> int:
        return 0

class C(B):
    def __init__(self) -> None:
        self.x = 4  # error: "x" is read-only

It seems that mypy should only allow overriding a read-only property with an attribute declared in the class body if the attribute has an initializer in the class body. For consistency, we should probably also use the same rule for overriding read-write properties.

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 reproducing the three inheritance examples from the issue and inspect mypy's handling of declared attributes overriding properties. Add coverage for the failing instance-assignment case and the accepted class-body initializer case, then verify that read-only and read-write properties follow the intended rule.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
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.