python / python/mypy

Nondeterministic type-var error with LiteralString-bounded TypeVars

Abierto
#20,528 3 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

After upgrading from mypy 1.19.0 to 1.19.1, we're experiencing nondeterministic type checking behavior:

  1. Without type: ignore[type-var]: Sometimes reports "Value of type variable 'S' of 'Response' cannot be 'object'" [type-var]
  2. With type: ignore[type-var]: Sometimes reports "Unused 'type: ignore[type-var]' comment" [unused-ignore]

The error state is inconsistent and appears related to PR #20345 (which fixed issue #20344 about nondeterministic behavior with tuple type vars).

Environment

  • Mypy version: 1.19.1
  • Python version: 3.13
  • Upgraded from: mypy 1.19.0 (no errors)

Example

Granted, this is a simplified, sanitized example I have extracted from our code base but I believe it highlights the case where the issue is happening

from typing import LiteralString


class Container[S: LiteralString, T]:
    """A container with a LiteralString key."""

    def __init__(self, key: S, value: T) -> None:
        self.key = key
        self.value = value


class Response[S: LiteralString, T]:
    """A response parameterized by LiteralString."""

    def __init__(self, container: Container[S, T]) -> None:
        self.container = container


def process[S: LiteralString, S1: LiteralString](
    containers: list[Container[S, int] | Container[S1, str]],
) -> dict[int, Response]:
    """Create responses from a union of containers with different LiteralString keys."""
    return {
        i: Response(container)  # May error: type-var or unused-ignore
        for i, container in enumerate(containers)
    }
Scenario 1: With type: ignore[type-var] comment
example.py:28: error: Unused "type: ignore[type-var]" comment  [unused-ignore]
Scenario 2: Without the comment (in different contexts)

Sometimes passes with no errors, sometimes shows:

example.py:28: error: Value of type variable "S" of "Response" cannot be "object"  [type-var]

I'm not able to nail down exactly when each scenario surfaces but hopefully this is enough to go on as it otherwise presents as a regression since 1.19.0

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 ejecutando el ejemplo proporcionado con mypy 1.19.0 y 1.19.1, tanto con el comentario type: ignore[type-var] como sin él, y compara los diagnósticos. Lee PR #20345 y issue #20344 sobre el comportamiento no determinista relacionado de los type-var de tuplas; se considera terminado cuando el caso de TypeVar acotado por LiteralString produce un resultado determinista y correcto.

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

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.