Reject invalid override of a property with a declared attribute
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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