Python:注释实例化 TypedDicts 的函数
我有一个函数 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论