修复 mypy 此类功能的最佳方法是什么
from typing import Union
def a(b: int) -> Union[int, str]:
if b:
return b
else:
return '2'
c: int = a(1)
d: str = a(0)
我的结果:
error: Incompatible types in assignment (expression has type "int | str", variable has type "int") [assignment]
error: Incompatible types in assignment (expression has type "int | str", variable has type "str") [assignment]
您可以使用
cast()
来强制执行实际类型:
from typing import cast
c = cast(int, a(1)) # => int
d = cast(str, a(0)) # => str
当然,这依赖于you对新类型的理解是正确的;如果你搞砸了,这样的
cast()
可能会花费你一两个小时:
e = cast(str, 42) # fine
reveal_type(e) # => str
另一种方法是使用
isinstance
检查。这更安全,但更冗长:
c = a(1) # int | str
if isinstance(c, int):
function_taking_int(c)
else:
function_taking_str(c)