-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Open
Labels
bugmypy got something wrongmypy got something wrongtopic-descriptorsProperties, class vs. instance attributesProperties, class vs. instance attributes
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.
Metadata
Metadata
Assignees
Labels
bugmypy got something wrongmypy got something wrongtopic-descriptorsProperties, class vs. instance attributesProperties, class vs. instance attributes