Args with a generic type will use the mother type, rather than a literal
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
Args with a generic type will use the mother type, rather than a literal
I noticed this issue while trying to chain together two lists with different types with itertools.chain.
To Reproduce
from typing import TypeVar
T = TypeVar('T')
class M:
pass
class C1(M):
def my_method(self) -> None:
pass
class C2(M):
def my_method(self) -> None:
pass
def test(*args: T) -> T:
return args[0]
result = test(C1(), C2())
result.my_method()
https://mypy-play.net/?mypy=latest&python=3.12&flags=strict&gist=d78c6875b87a3040126e1926b8f7ba0c
Expected Behavior
I expected to be able to run my_method, as all arguments have it defined. Instead the mother type is used. This issue can be mitigated by extracting the arguments, giving them a literal type, then unpack them into the function:
my_args: list[C1 | C2] = [C1(), C2()]
test(*my_args)
Actual Behavior
main.py:26: error: "M" has no attribute "my_method" [attr-defined]
I believe this happens because untyped lists defined with items will use the mother type of all items. I don't think this is very intuitive for args.
Visual Studio Code's Pylance does not give an error in this situation, even with the strict flag.
Your Environment
- Mypy version used: 1.9.0
- Mypy command-line flags: no flags
- Mypy configuration options from
mypy.ini(and other config files): no config - Python version used: 3.9, 3.10, 3.11, 3.12
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, die bereitgestellte mypy-play-Reproduktion mit den angegebenen Python- und mypy-Versionen auszuführen, und verfolge anschließend die Inferenz generischer Argumente für das Beispiel test(*args: T) -> T. Erledigt ist dies, wenn der Aufruf mit gemischten C1- und C2-Werten zu einem Typ inferiert wird, der my_method bereitstellt, ohne dass die dazwischenliegende annotierte Liste erforderlich ist, und eine Regressionstestabdeckung für dieses Verhalten vorhanden ist.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 42/100