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

Har*_*Har 2 type-hinting pycharm

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

我正在执行以下操作,但 PyCharm 无法识别它:

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

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

我为此使用 python 2.7。

use*_*698 5

多种方法可以指定类型提示的联合。

在 Python 2 和 3 中,您可以使用以下命令:

def add(a, b):
    """
    :type a: int | float | bool
    :type b: int | float | bool
    :rtype: int | float | bool 
    """
    return a + b
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

或者

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
Run Code Online (Sandbox Code Playgroud)

或者

from typing import Union


def add(a: Union[int, float, bool], b: Union[int, float, bool]) -> Union[int, float, bool]:
    return a + b
Run Code Online (Sandbox Code Playgroud)

  • @user2235698 和 @Har——这是不正确的;“typing”模块可以作为 Python 2.7+ 的第三方库下载,因此类型提示在 Python 2 和 Python 3 中都可用。 (3认同)