python / python/mypy

confusing behavior with TypeVars and multiple inheritance checks in 0.770

Abierto
#8,604 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

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

Descripción

Hi, I was just testing out 0.770 and I'm getting a surprising result:

from typing import TypeVar

class Foo(object):
    pass

FooOrStr = TypeVar('FooOrStr', Foo, str)

def doit(reset: bool, arg: FooOrStr) -> FooOrStr:
    if reset:
        if isinstance(arg, Foo):
            reveal_type(arg)
            arg = Foo()
        elif isinstance(arg, str):
            reveal_type(arg)
            arg = ''
        else:
            raise TypeError()
    return arg
test.py:12: note: Revealed type is 'test.Foo*'
test.py:12: note: Revealed type is 'test.<subclass of "str" and "Foo">'
test.py:13: error: Incompatible types in assignment (expression has type "Foo", variable has type "str")  [assignment]
test.py:15: note: Revealed type is 'builtins.str*'

Based on the latest blog post about 0.770 I suspect this is by design, but what can I do to work around it (short of adding some artificial method to make Foo incompatible with str)?

It would be good to add something to the docs about this, because I think it could be a fairly common trap. Also, I think adjusting the error message to clarify the relationship to multiple inheritance would help, e.g. variable has type Foo and 'test.<subclass of "str" and "Foo">'.

Thanks!

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 mypy 0.770 o el ejemplo de TypeVar y herencia múltiple del issue para reproducir los tipos revelados y el error de asignación. Lee la documentación relevante sobre TypeVar y el estrechamiento de tipos, así como las pruebas de diagnóstico, y documenta después el comportamiento, una solución alternativa y una redacción más clara para la relación entre Foo y el tipo de subclase inferido.

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

Evaluación

Stack tecnológico
python
Área
devtools, tooling
Tipo de issue
Documentación
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
30/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.