在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")
cast
和 isinstance
也不起作用。
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/