python / python/mypy

False positive `[operator]` on union of dicts with heterogeneous value types

Abierto
#18,236 3 comentarios 1 reacción 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

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

Descripción

Bug Report

If I take the union of two dicts with different value types, I cannot assign the result to a variable that is annotated with the resulting type. Doing so causes an error. Assigning to an non-annotated variable does not cause an error, which seems like the correct behavior.

Do I really need the annotation on d5 below? No. But I have a non-toy example of this in a code base where d5 is a type annotated attribute on an object, which results in the same error.

d1: dict[str, str] = {}
d2: dict[str, str | None] = {}

d3 = d1 | d2
reveal_type(d3)  # builtins.dict[builtins.str, Union[builtins.str, None]], aka dict[str, str | None]

# This is fine
d4: dict[str, str | None] = d3  # aka d1 | d2

# This isn't?
d5: dict[str, str | None] = d1 | d2

To Reproduce

See: https://mypy-play.net/?mypy=master&python=3.13&flags=show-error-codes&gist=2643cb3ff1ea956a1c4ed0869140d46d

Expected Behavior

I expect d5: dict[str, str | None] = d1 | d2 to be legal.

Actual Behavior

error: Unsupported operand types for | ("dict[str, str]" and "dict[str, str | None]") [operator].

Your Environment

  • Mypy version used: 1.13.0
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.12

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 con la reproducción mínima del issue o con su ejemplo de mypy-play enlazado, usando el contexto indicado de Python 3.12 y mypy 1.13.0. Compara la unión directa anotada con el caso de la variable intermedia y, después, verifica que la asignación directa ya no emita el error [operator], mientras que el tipo revelado siga siendo dict[str, str | None].

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

Evaluación

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

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.