[英]Is there a non-covariant `Type[T]`?
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
.假设我正在尝试为为用户定义类型注册反序列化器的库函数编写类型提示:用户应提供类型
T
以及函数decode: str -> T
。
The most natural way I can think to write this with python's PEP-484 type hints is the following:我能想到用 python 的 PEP-484 类型提示写这个的最自然的方法是:
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
对我来说不幸的是,
Type[T]
在T
中是协变的这一事实意味着这对 decode 函数不够严格:至少在 pyright 中,调用register_decoder(int, decode=str)
通过类型检查,类型变量T
解决为 union int | str
int | str
: 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
?有没有办法对这个方法进行类型提示,强制
decode
返回type_
的实例,所以这个例子会因为str
不返回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.可以完成这项工作的一件事是
Type[T]
的非协变等效项,它只接受确切的类对象T
而不是任何子类型,但我不确定 Python 中是否存在类似的东西。
Using mypy --strict
gives me the expected error.使用
mypy --strict
会给我预期的错误。 Must be something specific to the linter you are using.必须是特定于您正在使用的 linter 的东西。
from typing import Callable, Type, TypeVar
T = TypeVar("T")
def register_decoder(type_: Type[T], decode: Callable[[str], T]) -> None:
return
register_decoder(int, str)
>mypy --strict test.py
test.py:6: error: Argument 2 to "register_decoder" has incompatible type "Type[str]"; expected "Callable[[str], int]"
Found 1 error in 1 file (checked 1 source file)
>python --version
Python 3.9.5
>mypy --version
mypy 0.910
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.