Mypy似乎忽略了TypeVar类型的界限

2024-04-26 05:29:25 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我有一段代码如下:

from typing import Type, TypeVar, cast

class SuperClass:
    pass


T = TypeVar('T', bound=SuperClass)


def cast_to(obj: SuperClass, cast_to: Type[T] = SuperClass) -> T:
    return cast(cast_to, obj)

我把它保存在type_check.py。如果我在上面运行mypy,会收到以下错误消息:

type_check.py:10: error: Incompatible default for argument "cast_to" (default has type "Type[SuperClass]", argument has type "Type[T]")
type_check.py:11: error: Invalid type "cast_to"

从我对TypeVar中的bound的理解来看,只要TSuperClass的一个子类,就可以了。但是为什么mypy会在这里抛出错误呢?谢谢!你知道吗


Tags: topyobjdefaultchecktype错误error
1条回答
网友
1楼 · 发布于 2024-04-26 05:29:25

代码有两个问题:首先,cast_to函数的签名应该是:

def cast_to(obj: SuperClass, cast_to: Type[T] = Type[SuperClass]) -> T:

那么,在您的cast语句中,我不确定mypy是否允许您使用cast_to作为cast的第一个参数。相反,您可以尝试:

def cast_to(obj: SuperClass, cast_to: Type[T]) -> T:
    return cast(T, obj)

当然,使用这个定义,您将无法仅用一个参数调用cast_to。你知道吗


我现在要问:为什么你觉得你需要这么做?你确定你的设计好吗?cast应在非常特殊的情况下使用;文档说明:

Casts are used to silence spurious type checker warnings and give the type checker a little help when it can’t quite understand what is going on.

所以你应该严肃地质疑你的设计!再给我们一点你想要达到的目标的信息。也许有比你想做的更好更干净的设计。你知道吗

相关问题 更多 >