python / python/mypy

Overload ambiguity is ignored in `self`-annotated methods

Abierto
#11,347 5 comentarios 2 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

bug topic-overloads
Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Merge medio
1 d 18 h
PR fusionados (30 d)
54

Descripción

Bug Report

Per the title: mypy does not check for overload ambiguity in self-annotated methods.
Mypy will instead, effectively, ignore self and then return the first matching overload,
thus circumventing the usual Any that is returned when overload ambiguity is involved.
This has lead to a number of false positives in https://github.com/numpy/numpy/issues/20099 and (in part) https://github.com/numpy/numpy/issues/20072.

The conditions for triggering this bug are as following:

  • The callable is a method (things work fine for functions).
  • The method is overloaded.
  • self must be annotated with a parametrized generic.

To Reproduce

from typing import Any, Generic, overload, TypeVar, TYPE_CHECKING
import numpy as np

_CharType = TypeVar("_CharType", np.str_, np.bytes_)


class CharArray(Generic[_CharType]):
    @overload
    def strip(self: CharArray[np.str_], chars: str = ...) -> CharArray[np.str_]: ...
    @overload
    def strip(self: CharArray[np.bytes_], chars: bytes = ...) -> CharArray[np.bytes_]: ...


ar_any: CharArray[Any]
ar_str: CharArray[np.str_]
ar_bytes: CharArray[np.bytes_]

if TYPE_CHECKING:
    # The good
    reveal_type(ar_str.strip())  # E: Revealed type is "__main__.CharArray[numpy.str_]"
    reveal_type(ar_bytes.strip())  # E: Revealed type is "__main__.CharArray[numpy.bytes_]"

    # The bad
    # "__main__.CharArray[Any]" would be expected here due to overload ambiguity
    reveal_type(ar_any.strip())  # E: Revealed type is "__main__.CharArray[numpy.str_]"

    # Calling the method directly from the class does do the trick
    reveal_type(CharArray.strip(ar_any))  # E: Revealed type is "test.CharArray[Any]"

Your Environment

  • Mypy version used: 0.910
  • Mypy command-line flags: n.a.
  • Mypy configuration options from mypy.ini (and other config files): n.a.
  • Python version used: 3.9.6
  • Operating system and version: macOS 11.4

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 la reproducción de Python proporcionada con mypy y compara los tipos revelados para las llamadas al método sobrecargado. Traza la resolución de sobrecargas para métodos cuyo parámetro self es un genérico parametrizado; se considera terminado cuando la llamada ambigua CharArray[Any].strip() devuelve Any, mientras que los tipos self concretos conservan sus resultados específicos.

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

Evaluación

Stack tecnológico
numpy, python
Área
compilers, 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.