Skip to content

False positive error on subclass overriding a ClassVar #4715

@carljm

Description

@carljm

This seems to be a bug.

With the following code:

from typing import ClassVar

class Base:
    name: ClassVar[str]

class Sub(Base):
    name = "Sub"

mypy complains that :7: error: Cannot override class variable (previously declared on base class "Base") with instance variable.

But the assignment on the subclass is clearly at the class level. Assigning a value to a class attribute that has already been declared as one should not result in an error. I'd expect this error only if the assignment took place e.g. inside __init__.

Explicitly annotating the subclass assignment (name: ClassVar[str] = "Sub") gets rid of the error, but that repeated annotation should not be necessary.

Reproduced on mypy 0.580-dev-9374acf2d808905d392b2ec8ea52bfce03f9ecad under Python 3.6.4, with no flags or options.

I realize that inability to distinguish instance vs class attributes is a known mypy limitation (#1097), but in general it just results in false negatives. This seems worth a distinct issue since it appears that mypy is attempting to make the distinction, but doing so incorrectly, resulting in a false positive.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions