Union type narrowing behaves differently depending on argument position
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Python
- Estrellas
- 20.6k
- Forks
- 3.3k
- Métricas de merge de PR
- Métricas de PR pendientes
Descripción
Bug Report
In the following example the type narrowing of the union types works as expected if it appears in the first or second argument position, but breaks if it appears in position three (or later).
This issue probably falls into the topic-join-v-union.
To Reproduce
Example on mypy playground
from typing import Callable, TypeVar
T = TypeVar("T")
def func(
a: Callable[[], T],
b: Callable[[], T],
c: Callable[[], T],
) -> T:
raise NotImplementedError()
class Foo:
...
class Bar:
...
def make_foo() -> Foo:
raise NotImplementedError()
def make_bar() -> Bar:
raise NotImplementedError()
def make_foo_or_bar() -> Foo | Bar:
raise NotImplementedError()
x1: Foo | Bar = func(a=make_foo_or_bar, b=make_foo, c=make_bar)
x2: Foo | Bar = func(a=make_foo, b=make_foo_or_bar, c=make_bar)
x3: Foo | Bar = func(a=make_foo, b=make_bar, c=make_foo_or_bar)
Expected Behavior
The example should type check properly.
Actual Behavior
Inferring the return type works properly for x1 and x2, but it fails for x3 with:
Incompatible types in assignment (expression has type "object", variable has type "Foo | Bar") [assignment]
Considering that the code is fully valid and symmetric, there should not be a difference in the behavior.
Side note: The issue cannot be work-around at call site by just swapping the order of a and c in the func(...) call. Apparently it has to do with the order in which they appear in the function signature.
Your Environment
- Mypy version used: 1.6.1
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.10, 3.11
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Comienza con el reproductor del issue y ejecútalo con mypy 1.6.1 o la versión actual para confirmar la diferencia posicional. Rastrea la inferencia de tipos de los argumentos callable para func e investiga por qué el tercer parámetro produce object; estará terminado cuando x1, x2 y x3 pasen la comprobación de tipos de forma coherente.
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
- Bien especificado
- Aptitud para principiantes
- 35/100