Skip to content

Error when annotating a function that instantiates TypedDicts #12310

@RomeoDespres

Description

@RomeoDespres

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

Environment:

  • Mypy version used: 0.931
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.9.2
  • Operating system and version: Windows 10 21H1

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions