python / python/mypy

`TypeIs` narrowing of union type in a generic is not working

Abierto
#20,359 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

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

Descripción

Bug Report

Given an object of type int | bytes and a TypeIs function that narrows int | str | bytes into int | str, mypy correctly infers that the original object is really just int.

However, this doesn't work if the union is a generic parameter. That is, given Sequence[int | bytes] and a narrowing function from Sequence[int | str | bytes] to Sequence[int | str], mypy doesn't infer that the original is Sequence[int]. Instead, it infers that the original is Sequence[int | str].

I think this is a bug? But of course I might just be holding it wrong. Any help will be greatly appreciated.

To Reproduce

from typing import Callable, TypeIs, Sequence, assert_type

def check_plain(value: int | str | bytes) -> TypeIs[int | str]:
    return isinstance(value, int | str)

def check_sequence(seq: Sequence[int | str | bytes]) -> TypeIs[Sequence[int | str]]:
    return all(isinstance(value, int | str) for value in seq)

def works(value: int | bytes) -> None:
    assert check_plain(value)
    assert_type(value, int)

def doesnt(value: Sequence[int | bytes]) -> None:
    assert check_sequence(value)
    assert_type(value, Sequence[int])

https://mypy-play.net/?mypy=1.19.0&python=3.13&gist=100053f110206f3fdf37170ea75a3ca2

Actual Behavior

main.py:15: error: Expression is of type "Sequence[int | str]", not "Sequence[int]"  [assert-type]
Found 1 error in 1 file (checked 1 source file)

Your Environment

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

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 proporcionada con mypy 1.19.0 y confirma el assert_type fallido para el caso genérico de Sequence. Rastrea la lógica de narrowing de TypeIs para parámetros genéricos; se considera terminado cuando el ejemplo restringe value a Sequence[int] sin el error indicado, mientras que el caso simple sigue funcionando.

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

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.