python / python/mypy

Overloads not resolved correctly when argument is `Any` and return types use `TypeGuard` or `TypeIs`

Aperta
#17,579 8 commenti 2 reazioni 1 assegnatario Vedi su GitHub

@sobolevn ci sta già lavorando.

Dal 13/8/2024.

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

Descrizione

When overload matching is ambiguous due to an Any argument, mypy typically looks at the return types of the potential matches. If the return types differ, it evaluates the return type as Any to preserve the "gradual type guarantee". It apparently doesn't do this when the return types of the potential overload matches use TypeIs. See the example below, where mypy matches the first overload rather than detecting the ambiguity and evaluating Any.

from typing import Any, overload
from typing_extensions import TypeIs

@overload
def func1(x: str) -> TypeIs[str]:
    ...

@overload
def func1(x: int) -> TypeIs[int]:
    ...

def func1(x: Any) -> Any:
    return True

def func2(val: Any):
    if func1(val):
        reveal_type(val) # Should be Any

I discovered this problem because pyright has the same issue. I'm guessing that the underlying cause of the bug in mypy is similar. Pyright's logic was treating TypeIs[T] as equivalent to bool in this case, but TypeIs[T] should be treated as a subtype of bool. Also, TypeIs[X] is not equivalent to TypeIs[Y] unless X is equivalent to Y.

This bug affects a recent change in typeshed to the dataclasses.isdataclass function, as discussed here.

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.

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.