Skip to content

Assignment to classvar narrows type seemingly too much #17981

Closed
@wence-

Description

@wence-

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions