Descriptors and ClassVars
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
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
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia eseguendo il riproduttore Python fornito con mypy 1.1.1 e confronta i diagnostici per il field1 basato su descriptor e il normale field2 ClassVar. Traccia quindi la gestione delle assegnazioni ai membri coinvolta in questi diagnostici e aggiungi una copertura di regressione che dimostri che l’assegnazione basata su descriptor è accettata, mentre la normale assegnazione a ClassVar rimane un errore.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- devtools
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100