'Python: annotating a function that instantiates TypedDicts

I have a function f which takes as argument a TypedDict class, and returns an instance of this class.

I've tried the following implementation using TypeVar. However when passing around the result of f, mypy complains about it not having the correct type. I've narrowed it down to the snippet below:

from typing import Type, TypeVar, TypedDict


T = TypeVar("T")


def f(cls: Type[T]) -> T:
    return cls()


class Foo(TypedDict):
    pass


f_foo: Foo = f(Foo)

reveal_type(f(Foo))

The output of mypy is then:

test.py:15: error: Incompatible types in assignment (expression has type "Foo", variable has type "Foo")
test.py:17: note: Revealed type is "test.Foo*"

Why is the type of f(Foo) test.Foo* instead of TypedDict('test.Foo', {})?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source