Return type hint fails with multiple supplied type vars
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
I'm not 100% sure how to word this but mypy fails to detect the proper return type if multiple types are supplied. It works just fine if only a single type is specified.
This scenario works just fine with pyright/pylance.
To Reproduce
import typing as t
class BaseClass:
...
class Sub1(BaseClass):
...
class Sub2(BaseClass):
...
ClassType = t.TypeVar("ClassType", bound=BaseClass)
def testing_union() -> t.Union[Sub1, Sub2]:
res = sub_method(Sub1, Sub2)
reveal_type(res)
return res
def testing_single() -> Sub1:
res = sub_method(Sub1)
return res
def sub_method(*output_type: t.Type[ClassType]) -> ClassType:
return # type: ignore[return-value]
Expected Behavior
I expect mypy to work for both testing_union() and testing_single().
Actual Behavior
A return-value occurs in testing_union as it thinks the value is the bound base class. Using reveal_type we can see that mypy detects the type as BaseClass whereas pylance/pyright detects it as the expect3ed Sub1 | Sub2 type.

The output from the mypy check is
mypy-test.py:21: note: Revealed type is "mypy-test.BaseClass"
mypy-test.py:23: error: Incompatible return value type (got "BaseClass", expected "Union[Sub1, Sub2]") [return-value]
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used: mypy 1.0.0 (compiled: yes)
- Mypy command-line flags:
python -m mypy file.py - Mypy configuration options from
mypy.ini(and other config files): N/A - Python version used: Python 3.11.0
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne damit, den bereitgestellten Reproducer mit mypy 1.0.0 auszuführen, und vergleiche den aufgelösten Typ für mehrere gegenüber einzelnen Typargumenten. Verfolge das Verhalten der Typinferenz für die variadischen TypeVar-Argumente von sub_method; fertig ist es, wenn der Union-Fall Sub1 | Sub2 auflöst und die deklarierte Rückgabeprüfung besteht, ohne den Fall mit einem einzelnen Typ abzuschwächen.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- compilers, devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100