1

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', {})?

Roméo Després
  • 1,777
  • 2
  • 15
  • 30
  • what does the function reveal_type look like? When I run ```type(f(Foo))``` it yields ```dict``` which is what I would expect. – itprorh66 Mar 08 '22 at 15:37
  • 1
    @itprorh66 [`reveal_type` is a mypy internal](https://mypy.readthedocs.io/en/stable/common_issues.html#reveal-type). – AKX Mar 08 '22 at 15:39
  • Not familiar with mypy but see this for possible solution [How to force mypy's reveal_type to reveal super type?](https://stackoverflow.com/questions/64925028/how-to-force-mypys-reveal-type-to-reveal-super-type), it looks similar to your question. – itprorh66 Mar 08 '22 at 15:48
  • Thanks @itprorh66. My goal is not to fix the output of `reveal_type` though, but rather to get rid of the mypy error. – Roméo Després Mar 08 '22 at 15:54
  • 3
    Wild. After playing around with it, my best guess is that some kind of magic happens when you actually instantiate a `TypedDict` that doesn't translate via the `TypeVar`. Seems worth filing a mypy bug against. – Samwise Mar 08 '22 at 15:55
  • Thanks @Samwise - [done](https://github.com/python/mypy/issues/12310) – Roméo Després Mar 08 '22 at 16:10
  • It seems like a bug in **mypy** to me. In terms of **Pyright** this code is correct. – Paweł Rubin Mar 13 '22 at 09:16

0 Answers0