在Pycharm中,如何为类型提示指定联合?

In Pycharm, how to specify unions for type hinting?

有人知道如何为类型提示编写联合吗?

我正在执行以下操作,但未被 PyCharm 识别:

def add(a, b)
    # type: (Union[int,float,bool], Union[int,float,bool]) -> Union([int,float,bool])
    return a + b

为联合指定类型提示的正确方法是什么?

我为此使用 python 2.7。

在 Pycharm(版本 2016.2.2)中为我做以下工作:

from typing import Union

def test(a, b):
    # type: (Union[int, float, bool], Union[int, float, bool]) -> Union[int, float, bool]
    return a + b

Pycharm 可能会混淆,因为您的 return 类型中有额外的括号,或者可能是因为您忘记从 typing 模块导入 Union

many ways 可以为类型提示指定联合。

在 Python 2 和 3 中,您可以使用以下内容:

def add(a, b):
    """
    :type a: int | float | bool
    :type b: int | float | bool
    :rtype: int | float | bool 
    """
    return a + b

在 Python 3.5 中引入了 typing 模块,因此您可以使用以下之一:

from typing import Union

def add(a, b):
    # type: (Union[int, float, bool], Union[int, float, bool]) -> Union[int, float, bool]
    return a + b

from typing import Union

def add(a, b):
    """
    :type a: Union[int, float, bool]
    :type b: Union[int, float, bool]
    :rtype: Union[int, float, bool]
    """
    return a + b

from typing import Union


def add(a: Union[int, float, bool], b: Union[int, float, bool]) -> Union[int, float, bool]:
    return a + b