Descriptors and ClassVars
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
Have came across this issue from pyright
To Reproduce
# This sample tests the case where a member access is performed through
# an object using a field that is annotated as a ClassVar. Normally this
# is disallowed, but it is permitted if the type of the ClassVar is
# a descriptor object.
from __future__ import annotations
from typing import TYPE_CHECKING, ClassVar, Generic, Self, TypeVar, overload
T = TypeVar("T")
class Descriptor(Generic[T]):
if TYPE_CHECKING:
@overload
def __get__(self, instance: None, owner) -> Self:
...
@overload
def __get__(self, instance: object, owner) -> T:
...
def __get__(self, instance: object | None, owner) -> Self | T:
...
def __set__(self, instance: object, value: T) -> None:
...
def is_null(self) -> bool:
...
class Example:
field1: ClassVar = Descriptor[str]()
field2: ClassVar = ""
def reset(self) -> None:
self.field1 = ""
# This should generate an error because field2 isn't
# a descriptor object.
self.field2 = ""
Expected Behavior
Copied @erictraut comment:
ClassVar should work fine. If the class variable is assigned a descriptor, then the class variable will not be overwritten if you set the same attribute at the object level. So it sounds like mypy has a bug here. Pyright had a similar bug, which I recently fixed. Please report the bug to the maintainers of mypy.
Actual Behavior
classvar.py:39: error: Cannot assign to class variable "field1" via instance [misc]
classvar.py:43: error: Cannot assign to class variable "field2" via instance [misc]
Your Environment
- Mypy version used: 1.1.1
- Mypy command-line flags:
- Mypy configuration options from
mypy.ini(and other config files): - Python version used: 3.11.2
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne damit, den bereitgestellten Python-Reproducer mit mypy 1.1.1 auszuführen, und vergleiche die Diagnosen für das descriptor-gestützte field1 und das gewöhnliche ClassVar field2. Verfolge anschließend die Behandlung von Member-Zuweisungen, die an diesen Diagnosen beteiligt ist, und füge eine Regressionstestabdeckung hinzu, die zeigt, dass die descriptor-gestützte Zuweisung akzeptiert wird, während die gewöhnliche ClassVar-Zuweisung weiterhin ein Fehler bleibt.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100