Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reject invalid override of a property with a declared attribute #14413

Open
JukkaL opened this issue Jan 9, 2023 · 0 comments
Open

Reject invalid override of a property with a declared attribute #14413

JukkaL opened this issue Jan 9, 2023 · 0 comments
Labels
bug mypy got something wrong topic-descriptors Properties, class vs. instance attributes

Comments

@JukkaL
Copy link
Collaborator

JukkaL commented Jan 9, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-descriptors Properties, class vs. instance attributes
Projects
None yet
Development

No branches or pull requests

1 participant