函数返回类型联合的赋值中的类型不兼容

问题描述 投票:0回答:1

修复 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]
python-3.x mypy
1个回答
0
投票

您可以使用

cast()
来强制执行实际类型:

(游乐场链接:mypyPyright

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
检查。这更安全,但更冗长:

(游乐场链接:mypyPyright

c = a(1)  # int | str

if isinstance(c, int):
  function_taking_int(c)
else:
  function_taking_str(c)
© www.soinside.com 2019 - 2024. All rights reserved.