Python:注释实例化 TypedDicts 的函数

发布于 2025-01-13 00:45:36 字数 711 浏览 2 评论 0原文

我有一个函数 f ,它接受 TypedDict 类作为参数,并返回该类的实例。

我已经使用 TypeVar 尝试了以下实现。然而,当传递 f 的结果时,mypy 抱怨它没有正确的类型。我将其范围缩小到下面的代码片段:

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))

mypy 的输出如下:

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*"

为什么 f(Foo) 的类型是 test.Foo* 而不是 TypedDict('test.Foo', {})?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文