询问 Union[...] 类型的 isinstance

Ore*_*lom 7 python types mypy

我正在尝试询问isinstance有关用户定义类型的问题ConstData = Union[int, str]::

from typing import Union, Optional
ConstData = Union[int, str]
def foo(x) -> Optional[ConstData]:
    if isinstance(x, ConstData):  # <--- this doesn't work
    # if isinstance(x, (int, str)): <--- this DOES work ...
        return x
    return None
Run Code Online (Sandbox Code Playgroud)

不幸的是,它不起作用:

$ mypy main.py
main.py:4: error: Parameterized generics cannot be used with class or instance checks
main.py:4: error: Argument 2 to "isinstance" has incompatible type "object"; expected "Union[type, Tuple[Union[type, Tuple[Any, ...]], ...]]"
Found 2 errors in 1 file (checked 1 source file)
Run Code Online (Sandbox Code Playgroud)

有什么优雅的方法来解决这个问题吗?

hus*_*sic 2

关于:

“尽管如此,if isinstance(x, get_args(ConstData)): return xmypy 仍无法推断出它x具有正确的返回类型。它抱怨它是Any

我认为这是一个错误reveal_type(),Mypy 理解类型的缩小xtest()正如您在下面的代码中看到的,使用以下命令调用时不会引发错误x

def test(k:Union[int, str]) -> None:
    pass


def foo(x: Any) -> Optional[ConstData]:
    if isinstance(x, get_args(ConstData)):
        reveal_type(x)  # Mypy: Revealed type is "Any"
        test(x)  # Mypy: no error
        return x  # Mypy: no error
    return None
Run Code Online (Sandbox Code Playgroud)