是否有非交流`type [t]`?
假设我正在尝试为库函数编写类型提示,该库函数为用户定义的类型注册了求职者:用户应提供类型t
以及函数decode:str-&gt ; t
。
我认为使用Python的Pep-484类型提示写这句话的最自然方法是:
from typing import Callable, Type, TypeVar
T = TypeVar("T")
def register_decoder(type_: Type[T], decode: Callable[[str], T]):
...
不幸的是,对我而言,type [t]
在t
中是协变量的事实。意味着这对解码功能不够严格:至少在Pyright中,Invocation register_decoder(int,decode = str)
通过Type 使用类型变量t
已解决作为联合int | str
:
是否有一种键入此方法的方法来实施decode
返回类型_
的实例的约束。 ,以便此示例引起错误,因为str
不返回int
?可以完成这项工作的一件事是类型[t]
的非交流,仅接受 extcent class对象t
而不是任何任何亚型,但我不确定在Python中存在类型。
Suppose I'm trying to write type hints for a library function that registers a deserializer for a user-defined type: the user should provide a type T
along with a function decode: str -> T
.
The most natural way I can think to write this with python's PEP-484 type hints is the following:
from typing import Callable, Type, TypeVar
T = TypeVar("T")
def register_decoder(type_: Type[T], decode: Callable[[str], T]):
...
Unfortunately for me, the fact that Type[T]
is covariant in T
means this is not quite strict enough on the decode function: at least in pyright, the invocation register_decoder(int, decode=str)
passes typecheck, with the type variable T
resolved as the union int | str
:
Is there a way to type-hint this method that enforces the constraint that decode
returns instances of type_
, so that this example raises an error because str
does not return int
? One thing that would do the job is a non-covariant equivalent of Type[T]
that accepts only the exact class object T
rather than any subtype, but I'm not sure anything like this exists in Python.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
mypy -strict
给我预期的错误。必须是特定于您使用的衬里的东西。Using
mypy --strict
gives me the expected error. Must be something specific to the linter you are using.