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

inherited ClassVar #21

Open
beauxq opened this issue Mar 12, 2025 · 2 comments
Open

inherited ClassVar #21

beauxq opened this issue Mar 12, 2025 · 2 comments

Comments

@beauxq
Copy link

beauxq commented Mar 12, 2025

In the pyrefly playground, I tried this:

from typing import ClassVar


class B:
    x: ClassVar[int | str] = 0


class C(B):
    x = "random"  # pyrefly reports error here "Class member `x` overrides parent class `B` in an inconsistent manner"

But it is not inconsistent with what B declares. - x should be ok as a str

If you want to go further, this is also an opportunity to be better than mypy and pyright:

from typing import ClassVar, reveal_type


class B:
    x: ClassVar[int | str] = 0


class C(B):
    x = "random"


class D(C):
    x = 1  # mypy complains where it shouldn't


class E(D):
    x = b"3"  # pyright doesn't complain where it should


def foo(b: type[B]) -> None:
    x = b.x
    reveal_type(x)
    if isinstance(x, int):
        print(x + 8)
    else:
        print(x + "8")


foo(E)

The annotation of x in B should apply to all subclasses

@yangdanny97
Copy link
Contributor

Thanks for the report! Fully supporting ClassVar is on our list of TODOs here: #16

@samwgoldman
Copy link
Member

Is this behavior described anywhere? If not in the spec, is this something that mypy and/or pyright do? Based on the spec alone, it’s not clear to me why ClassVar annotations would be implicitly inherited. Maybe I missed the part of the spec that mentions this behavior?

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

No branches or pull requests

3 participants