python / python/mypy

annotations on `self` are not understood with `Protocol`s

Abierto
#16,291 5 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

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

Descripción

Bug Report

When interpreting a given type as a given Protocol, annotations on self in the Protocol are apparently ignored.

To Reproduce

mypy-play.net



from __future__ import annotations

from typing import *



                          #━━━━━━━━━━━━━━━━━#
                          #  EXISTING CODE  #
                          #━━━━━━━━━━━━━━━━━#


class ConcreteClass:

    # here 'transform()' is used, but we might use '__neg__()' or
    # '__invert__()' in a similar way (so many built-in/third-party
    # classes would qualify as 'TransformAware')

    def transform(self) -> int:
        return id(self)



                           #━━━━━━━━━━━━━━━━#
                           #  LIBRARY CODE  #
                           #━━━━━━━━━━━━━━━━#

# this can be changed


Ico = TypeVar('Ico', covariant=True)        # input, covariant
Oco = TypeVar('Oco', covariant=True)        # output, covariant


class TransformAware(Protocol[Ico, Oco]):

    def transform(self: Ico) -> Oco: ...



                      #━━━━━━━━━━━━━━━━━━━━━━━━━#
                      #  DEMONSTRATE PROBLEMS:  #
                      #━━━━━━━━━━━━━━━━━━━━━━━━━#


I = TypeVar('I')                            # input
O = TypeVar('O')                            # output


def interpret_transform_aware(_: Type[TransformAware[I, O]]) -> Tuple[I, O]:
    i: I
    o: O
    return i, o


reveal_type(interpret_transform_aware(ConcreteClass))
        # actual output:
        #   note: Revealed type is "Tuple[<nothing>, builtins.int]"
        # expected output:
        #   note: Revealed type is "Tuple[ConcreteClass, int]"



                           #───────────────#
                           #  MOTIVATION:  #
                           #───────────────#


class TransformDriver(Generic[I, O]):

    def __init__(self, klass: Type[TransformAware[I, O]]): ...

    def transform_value(self, value: I) -> O:
        use_value = cast(TransformAware[I, O], value)
        return use_value.transform()

Expected Behavior

(See: inline comments.)

Interpreting ConcreteClass as TransformAware should correctly infer both type variables.

Actual Behavior

(See: inline comments.)

Mypy gives the type of Ico as <nothing>.

Your Environment

  • Mypy version used: 1.6.1
  • Mypy command-line flags: (none necessary)
  • Mypy configuration options from mypy.ini (and other config files): (none necessary)
  • Python version used: 3.8, 3.11

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

Empieza con el reproductor de mypy-play.net y el código de gestión de Protocol; el payload no menciona ningún archivo del repositorio ni ningún test. Rastrea cómo se usan las anotaciones en self al interpretar ConcreteClass como TransformAware y añade cobertura que muestre que ambas variables de tipo se infieren como ConcreteClass e int.

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
38/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.