是否有非交流`type [t]`?

发布于 2025-02-11 00:30:15 字数 991 浏览 2 评论 0原文

假设我正在尝试为库函数编写类型提示,该库函数为用户定义的类型注册了求职者:用户应提供类型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:

pyright's inference of 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 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

橘味果▽酱 2025-02-18 00:30:15

使用mypy -strict给我预期的错误。必须是特定于您使用的衬里的东西。

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

Using mypy --strict gives me the expected error. Must be something specific to the linter you are using.

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文