python - 关于类型类型的 Mypy 断言

标签 python mypy

在Python中,我们可以通过这种方式给一个变量赋值类型,并通过mypy的typecheck:

from typing import Type, Union


class Foo:
    pass


MyType: Type[Foo] = Foo

同样,我们也可以使用Union进行打字

from typing import Type, Union


class Foo:
    pass


class Bar:
    pass


def func(is_bar: bool) -> Union[Type[Foo], Type[Bar]]:
    if is_bar:
        return Bar
    else:
        return Foo

知道 is_bar 的值,在调用 func 进行类型缩小后使用断言是完全合理的。

但是,断言似乎对 MyType 根本不起作用,因为 mypy 对以下代码示例给出了错误:

MyType = func(True)

assert MyType is Bar  
# `assert MyType is Type[Bar]` gives the same result

Test: Bar = MyType  # Incompatible types in assignment (expression
                    # has type "Union[Type[Foo], Type[Bar]]",
                    # variable has type "Bar")

castisinstance 也不起作用。

MyType = func(True)
cast(Type[Bar], MyType)
Test: Bar = MyType  # MyType is considered `Type[Bar] | Type[Foo]`
MyType = func(True)
assert isintance(MyType, Type[Bar])
Test: Bar = MyType  # MyType is considered `Type[Bar] | Type[Foo]`

我的问题是:如何对类型的类型进行类型缩小? 还是 mypy 的限制?如果是这样,解决方法是什么?

相关:

最佳答案

cast 助手返回它的约束参数,它实际上并没有改变它的参数被约束。

cast 到所需的 Type[...] 并分配或使用结果:

Test = cast(Type[Bar], MyType)
reveal_type(Test)  # note: Revealed type is "Type[so_testbed.Bar]"

关于python - 关于类型类型的 Mypy 断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68540528/

相关文章:

python - 使用 MyPy 的项目中的 FastAPI/Pydantic

python - 如何检查字符串是否是 mypy 的字符串文字?

python - 哪个python静态检查器可以捕获 'forgotten await'问题?

python - OpenCV 相机标定旋转 vector 到矩阵

python - 在小部件中嵌入 QGraphics

python - 特定行出现了多少次?

python - 选择随机 Action 的 Tensorflow 代理

python - 在 python 字典中为 mypy 指定键

python - 当子类和父类都满足祖 parent 类型定义时,为什么 mypy 会报告类型不兼容?

python - 如何为用户赋予角色以使用react