Python打字(或mypy)如何处理与IsInstance检查中的联合绑定的TypeVar?
我有以下代码:
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”)
。
我认为这应该是有效的,因为
- str-> str
- 子类(str) - >子类(str)
- int - > int
- 子类(int) - >子类(int)
- 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
- str -> str
- subclass(str) -> subclass(str)
- int -> int
- subclass(int) -> subclass(int)
- 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 usingTypeVar["T", str, int]
won't work either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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