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

Assignment to classvar narrows type seemingly too much #17981

Open
wence- opened this issue Oct 17, 2024 · 0 comments
Open

Assignment to classvar narrows type seemingly too much #17981

wence- opened this issue Oct 17, 2024 · 0 comments
Labels
bug mypy got something wrong

Comments

@wence-
Copy link

wence- commented Oct 17, 2024

Bug Report

Consider (https://mypy-play.net/?mypy=latest&python=3.12&gist=8afb9e0642a24aad8c26f3d22045ce18)

from typing import ClassVar

class Base:
    x : ClassVar[tuple[str, ...]] = ()
    
class Concrete(Base):
    x = ("foo",)
    
class Derived(Concrete):
    x = ("foo", "bar")
    
    
reveal_type(Base.x) # -> tuple[str, ...]
reveal_type(Concrete.x) # -> tuple[str]
reveal_type(Derived.x) # -> error

So I have a base class with a class attribute of type tuple[str, ...], I expect that deriving from this base class and assigning a concrete value should be fine.

However, mypy narrows the type of Concrete.x to tuple[str], and then if I try and derive from Concrete, tuple[str, str] is incompatible with tuple[str], so I can't assign a two-tuple to the class attribute in Derived.

Now, if the type of x really were tuple[str], this would be fine. But I think I've explicitly said "it's a tuple of any length", and both ("foo",) and ("foo", "bar") satisfy is-a tuple[str, ...].

Expected Behavior

I expect mypy to use the type annotation I've provided on the base class, and maintain that the type of x is always tuple[str, ...].

Output

main.py:10: error: Incompatible types in assignment (expression has type "tuple[str, str]", base class "Concrete" defined the type as "tuple[str]")  [assignment]
main.py:13: note: Revealed type is "builtins.tuple[builtins.str, ...]"
main.py:14: note: Revealed type is "tuple[builtins.str]"
main.py:15: error: Cannot determine type of "x"  [has-type]
main.py:15: note: Revealed type is "Any"
Found 2 errors in 1 file (checked 1 source file)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

1 participant