python / python/mypy

Descriptors and ClassVars

Abierto
#14,969 2 comentarios 1 reacción 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

bug topic-descriptors
Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

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

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza ejecutando el reproductor de Python proporcionado con mypy 1.1.1 y compara los diagnósticos para el field1 respaldado por un descriptor y el field2 ClassVar ordinario. Rastrea después el manejo de asignaciones a miembros implicado en esos diagnósticos y añade cobertura de regresión que demuestre que la asignación respaldada por un descriptor se acepta, mientras que la asignación ordinaria a ClassVar sigue siendo un error.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
python
Área
devtools
Tipo de issue
Error
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.