Skip to content

False positive error on subclass overriding a ClassVar #4715

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

Closed
carljm opened this issue Mar 10, 2018 · 4 comments · Fixed by #4718
Closed

False positive error on subclass overriding a ClassVar #4715

carljm opened this issue Mar 10, 2018 · 4 comments · Fixed by #4718

Comments

@carljm
Copy link
Member

carljm commented Mar 10, 2018

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.

@gvanrossum
Copy link
Member

Agreed this is fishy. Do you feel up to submitting a PR to fix this?

@carljm
Copy link
Member Author

carljm commented Mar 10, 2018

I can try to find time to look at it soon.

@lokhman
Copy link

lokhman commented May 6, 2022

I'm getting this error in the recent version of MyPy. Was the merged fix overridden or rolled back?

@AlexWaygood
Copy link
Member

AlexWaygood commented May 6, 2022

@lokhman, commenting on an issue that's been closed for 4 years isn't the best way to discuss a problem ;)

I'd recommend opening a new issue with a minimal, reproducible example of the code that doesn't type check. The code in the original example in this issue type-checks fine for me on mypy 0.950, even using mypy --strict, so I suspect that your problem is a slightly different one to the one that was discussed in this issue.

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 a pull request may close this issue.

4 participants