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

fix: Allow ClassVar descriptors to be assigned to from instances #17295

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

bzoracler
Copy link
Contributor

Fixes #14969. Allows the following:

from typing import Any, ClassVar

class D:
    def __set__(self, inst: Any, value: int) -> None: pass

class A:
    x: ClassVar[D] = D()

a = A()
a.x = 0  # OK
a.x = '0'  # E: Incompatible types in assignment (expression has type "str", variable has type "int")

Currently, a.x = 0 errors with Cannot assign to class variable "x" via instance [misc] (see mypy Playground).

  • The example in Descriptors and ClassVars #14969 will still error because ClassVar there is not specified with a type (an unannotated ClassVar is equivalent to ClassVar[Any]).
  • Unlike in other annotation contexts, I didn't think it was a good idea to be permissive with Any, due to the potential creep of false negatives.

Originally created as part of PR #17170, but I forgot about that PR and deleted the fork.

Comment on lines +32 to +35
a.x = 0 # E: Item "str" of "Union[str, D, Self, int]" has no attribute "__set__" \
# E: Item "A" of "Union[str, D, Self, int]" has no attribute "__set__" \
# E: Item "int" of "Union[str, D, Self, int]" has no attribute "__set__" \
# E: Cannot assign to class variable "x" via instance
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This error is in imitation of the following:

var: str | list[object] | int | None
var.append  # E: Item "None" of "str | list[object] | int | None" has no attribute "append" [union-attr] \
            # E: Item "int" of "str | list[object] | int | None" has no attribute "append" [union-attr] \
            # E: Item "str" of "str | list[object] | int | None" has no attribute "append" [union-attr]

Copy link
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

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 this pull request may close these issues.

Descriptors and ClassVars
1 participant