Skip to content

Allow class variable as implementation for read only attribute#14081

Merged
ilevkivskyi merged 2 commits intopython:masterfrom
ilevkivskyi:proto-property-classvar
Nov 16, 2022
Merged

Allow class variable as implementation for read only attribute#14081
ilevkivskyi merged 2 commits intopython:masterfrom
ilevkivskyi:proto-property-classvar

Conversation

@ilevkivskyi
Copy link
Copy Markdown
Member

Fixes #10289

Unless I am missing something, this indeed looks safe, so I am going to allow this.

cc @JukkaL

@github-actions
Copy link
Copy Markdown
Contributor

According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉

@bzoracler
Copy link
Copy Markdown
Contributor

bzoracler commented Nov 13, 2022

If x: Foo = Bar() is allowed to pass with the example in #10289, then should Foo be allowed to override FooParent?

from typing import *

class FooParent(Protocol):
    foo: ClassVar[int]

class Foo(FooParent, Protocol):
    @property
    def foo(self) -> int:  # Signature of "foo" incompatible with supertype "FooParent" [override]
        ...

class Bar:
    foo: ClassVar[int]

x: Foo = Bar()  # Expected to pass
y: FooParent = Bar()  # Expected to pass (?)

@ilevkivskyi
Copy link
Copy Markdown
Member Author

No, it should not. First, from Bar <: Foo and Bar <: FooParent one cannot conclude any subtyping between Foo vs FooParent. Second, it is actually unsafe, foo can be set freely on Type[FooParent], while on Type[Foo] it is at most read-only.

FWIW the opposite is true, FooParent should be allowed to override Foo (and it looks like it is allowed). So it looks like this PR actually fixes a hole in transitivity of subtyping.

@ilevkivskyi ilevkivskyi merged commit 6a7c7cd into python:master Nov 16, 2022
@ilevkivskyi ilevkivskyi deleted the proto-property-classvar branch November 16, 2022 13:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Protocol member expected instance variable, got class variable

2 participants