python / python/mypy

Inconsistent "Incompatible return type" error when `List[int]` is returned for `List[Union[str, int]]` when layered up with Tuple/Union

Aperta
#17,868 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug topic-type-context
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Bug Report

When layering up some Union/Tuple checks, at some point the type checking suddenly gets a lot more strict and starts failing, as if it's unable to fully parse the type checks anymore.

It's possibly related to this, but it doesn't explain why the behaviour changes only once it's wrapped under other things: https://github.com/python/mypy/issues/3351

To Reproduce

Here's a minimal reproducible example that shows how it works fine until it suddenly doesn't.

from typing import Union, Tuple, List

# Just to reduce the noise
S = Union[int, str]
L = List[S]

# It works with `([int],)`
def func_works1() -> Tuple[L]:
    return [1],
    
# It works with `([int, str],)`
def func_works2() -> Tuple[L]:
    return [1, 'a'],

# It works with `int | [int]`
def func_works3() -> Union[S, L]:
    return [1]

# It works with `(int,) | ([int],)` if returning (int,)
def func_works4() -> Union[Tuple[S], Tuple[L]]:
    return 1,

# It fails with `(int,) | ([int],)` if returning ([int],)
def func_fail1() -> Union[Tuple[S], Tuple[L]]:
    return [1],
main.py:21: error: Incompatible return value type (got "tuple[list[int]]", expected "tuple[int | str] | tuple[list[int | str]]")  [return-value]

# It fails with `(int,) | ([int],)` if returning ([int, str],)
def func_fail2() -> Union[Tuple[S], Tuple[L]]:
    return [1, 'a'],
main.py:25: error: Incompatible return value type (got "tuple[list[object]]", expected "tuple[int | str] | tuple[list[int | str]]")  [return-value]

https://mypy-play.net/?mypy=latest&python=3.12&gist=9477b2d4dab01919bef1aa6d2911f648

Expected Behavior

It passes the test.

Actual Behavior

In the code above. It complains that List[int] is not a valid List[Union[int | str]]. According to the issue linked above, this may not be wrong, but the behaviour is inconsistent as to when it flags it as wrong.

Your Environment

  • Mypy version used: 1.11.2
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): I just run py -m mypy without any config files.
  • Python version used: 3.7, 3.11

Edit
This is nothing to do with the bug report, but in case anyone finds this issue with a similar use case, this is the fully working solution I've ended up with:

S = Union[int, str]
T = TypeVar('T', S, List[S])
FuncType = Tuple[T, T]

def func() -> FuncType:
   return a, b

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia eseguendo il riproduttore minimo con mypy 1.11.2 e confronta i casi Union/Tuple/List non racchiusi con func_fail1 e func_fail2. Leggi l’issue #3351 per il comportamento correlato, quindi traccia il percorso del controllo dei tipi per le espressioni Union e Tuple annidate; il lavoro è completato quando i casi segnalati passano in modo coerente con un test di regressione.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
compilers
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.