Type[T] -> T has a strange behaviour · Issue #9003 · python/mypy (original) (raw)

This bug report is coming from #8946 and ltworf/typedload#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.