Python打字(或mypy)如何处理与IsInstance检查中的联合绑定的TypeVar?

发布于 2025-01-29 04:49:50 字数 757 浏览 1 评论 0原文

我有以下代码:

from typing import TypeVar, Union

T = TypeVar("T", bound=Union[str, int])

def a(x: T) -> T:
    if isinstance(x, str):
        return x
    return x

但是mypy(使用- strict)提高错误:不兼容的返回值类型(get“ str”,“预期”,“ t”)

我认为这应该是有效的,因为

  1. str-> str
  2. 子类(str) - >子类(str)
  3. int - > int
  4. 子类(int) - >子类(int)
  5. str | int-> str | INT

因此,Mypy有一个错误,或者(更有可能)我对TypeVars的了解还不够好。

值得注意的:

  • 我想拥有str-> str,int-> int映射,因此仅使用union [str,int]无法使用。
  • 有时使用类型union [str,int]的变量调用此功能,因此使用typeVar [“ t”,str,int]也无法正常工作。

I have the following code:

from typing import TypeVar, Union

T = TypeVar("T", bound=Union[str, int])

def a(x: T) -> T:
    if isinstance(x, str):
        return x
    return x

but mypy (with --strict) raises error: Incompatible return value type (got "str", expected "T").

In my opinion this should be valid, since

  1. str -> str
  2. subclass(str) -> subclass(str)
  3. int -> int
  4. subclass(int) -> subclass(int)
  5. str | int -> str | int

So either mypy has a bug, or (more likely) my knowledge of TypeVars is not good enough.

Worth noticing:

  • I want to have the str -> str, int -> int mapping, so simply using Union[str, int] won't work.
  • This function is called sometimes with variables of type Union[str, int], so using TypeVar["T", str, int] won't work either.

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

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

发布评论

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