Type[T] -> T has a strange behaviour
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
This bug report is coming from https://github.com/python/mypy/issues/8946 and https://github.com/ltworf/typedload/issues/132
Basically the pattern
def f(t: Type[T]) -> T: ...
Works for some types but not others, and I can't see a pattern. For example it will work for a NamedTuple but not for a Tuple.
See this example:
from typing import *
from dataclasses import dataclass
T = TypeVar('T')
@dataclass
class P:
a: int
class Q(NamedTuple):
a: int
def create(t: Type[T]) -> T: ...
# These ones work
reveal_type(create(int))
reveal_type(create(str))
reveal_type(create(List[int]))
reveal_type(create(Dict[int, int]))
reveal_type(create(Q))
reveal_type(create(P))
# These do not
reveal_type(create(Tuple[int]))
reveal_type(create(Union[int,str]))
reveal_type(create(Optional[int]))
Now in the older mypy, the ones that do not work would just be understood as Any, which is absolutely not the intended behaviour. In the latest release instead they fail with error: Argument 1 to "create" has incompatible type "object"; expected "Type[<nothing>]" (and I have no idea of what this means).
Anyway in my view, all of the examples provided should work.
In case I'm wrong, then none of them should work, and probably a way to achieve this is needed.
Background: I am working on a library to load json-like things into more typed classes, and it promises to either return an object of the wanted type, or fail with an exception.
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
Beginnen Sie mit dem bereitgestellten Python-Reproducer und führen Sie mypy für jeden reveal_type-Aufruf aus, wobei Sie die funktionierenden Fälle mit Tuple[int], Union[int, str] und Optional[int] vergleichen. Verfolgen Sie, wie Type[T] und TypeVar[T] für diese Aufrufe inferiert werden; abgeschlossen ist die Aufgabe, wenn die Beispiele konsistente, beabsichtigte inferierte Typen aufweisen oder das unterstützte Verhalten eindeutig dokumentiert und durch Regressionstests abgedeckt ist.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- compilers
- Issue-Typ
- Bug
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 30/100