python / python/typeshed

Several methods on built-in types are too strict.

Abierto
#15,271 4 comentarios 3 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Lenguaje dominante
Python
Estrellas
5.1k
Forks
2.1k
Merge medio
1 d 19 h
PR fusionados (30 d)
82

Descripción

I have identified several methods on built-in types that are too strict and can cause annoying false positives:

  • set and frozenset methods (#15470, #15160)
  • dict.{get, pop} (#15471)
  • list.{count, index, remove} (#15472)
  • MutableSet.discard
  • Mapping.get
  • MutableMapping.pop
  • Sequence.{count, index}
  • MutableSequence.remove
  • probably some more.

It seems like the annotations for these were designed to help detect user errors. For instance, we know that .get on a dict[int, int] will always return the default as the types are incompatible, and so .get was restricted in typeshed to only accept the key type. However, this hurts, even in simple cases like using literals:

from typing import Mapping, Literal

def demo_get(
    d: Mapping[Literal["foo", "bar"], int],
    dynamic_key: str,
) -> None:
    # No overload variant of "get" of "Mapping" matches argument type "str"
    d.get(dynamic_key)  

def demo_sub(
    left: set[Literal["foo", "bar"]],
    right: set[str],
) -> None:
    # Unsupported operand types for - ("set[Literal['foo', 'bar']]" and "set[str]")
    left - right

I believe typeshed is trying to act as a linter here, which shouldn't be its job. Type-checkers and type-informed linters are better at this and can use more complex logic.

For example, in the set difference case set[A] - set[B], the proper test would be to check whether the types have a non-empty intersection or not. The same could be said for Mapping[K, V].get(K2).

Related Topics:

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 localizando los stubs de typeshed para los métodos indicados de dict, list, set, Mapping, Sequence y Mutable*, y después lee las issues relacionadas 8219, 9155 y 9004. El alcance aún no está definido porque la issue también menciona métodos adicionales probables; para darlo por terminado se requiere acordar el conjunto de APIs afectadas y aplicar cambios coherentes en las anotaciones.

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

Evaluación

Stack tecnológico
python
Área
tooling
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Tranquilo
Claridad
Necesita aclaración
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.