python / python/mypy

Set and Dict generalizing the type unnecessarily

Abierto
#17,238 0 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

See these two example functions:

def f(items: list[str] | list[int]) -> None:
    items_as_set: set[str] | set[int] = set(items)

def g(key_to_count: dict[str, float] | dict[int, float]) -> None:
    key_to_count_2: dict[str, float] | dict[int, float] = {k: v for k, v in key_to_count.items()}

Mypy 1.10.0 complains about the assignment in each of them:

test_mypy_dict.py:2: error: Incompatible types in assignment (expression has type "set[object]", variable has type "set[str] | set[int]")  [assignment]
test_mypy_dict.py:5: error: Incompatible types in assignment (expression has type "dict[str | int, float]", variable has type "dict[str, float] | dict[int, float]")  [assignment]

To Reproduce

Playground gist: https://mypy-play.net/?mypy=latest&python=3.12&gist=83bde5f3f11470e94b6a680158649641

Expected Behavior

The set() or dict() operation applied on a variable that is either a list[str] | list[int] is always either a set[str] or set[int]. The same applies to function g using a dict. Thus the functions should not raise a mypy error.

Workarounds

I tried two workarounds:

  • Using a mixed type of list[str | int]. However, I get the type list[str] | list[int] by an external function, thus this is not compatible.
  • Using a generic. This is not working either.

See the playground gist: https://mypy-play.net/?mypy=latest&python=3.12&gist=264490179628a0a214a2e5bd947b8ccf
image

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 las dos reproducciones en Python del issue, incluidos los ejemplos de mypy-play enlazados, y compara los tipos inferidos y los errores de asignación para set() y la dict comprehension. Traza el flujo de comprobación de tipos para estas expresiones de constructor y comprehension; se considera terminado cuando ambas funciones pasan la comprobación de tipos sin errores, preservando la unión de tipos de contenedor homogéneos.

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

Evaluación

Stack tecnológico
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.