mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Reject invalid override of a property with a declared attribute

Open JukkaL opened this issue 3 years ago • 0 comments

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.

JukkaL avatar Jan 09 '23 11:01 JukkaL