【问题标题】:In Pycharm, how to specify unions for type hinting?在 Pycharm 中,如何为类型提示指定联合?
【发布时间】:2017-01-13 01:34:00
【问题描述】:

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

我正在执行以下操作,但 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 type-hinting


    【解决方案1】:

    在 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 可能会因为返回类型中的额外括号而感到困惑,或者可能是因为您忘记从 typing 模块导入 Union。

    【讨论】:

    • 我使用的是 python 2.7,我无法访问打字模块,是否仅适用于 python 3 的 Union?
    • @Har - 你可以通过 pip install typing 在 Python 2.7 上安装 typing 模块。 typing 模块已添加到 Python 3.5 的标准库中,可作为 Python 2.7 和 Python 3.2 - 3.4 上的第 3 方库安装。
    【解决方案2】:

    有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
    

    【讨论】:

    • 这是否意味着基于 PEP 的类型提示仅在 python 3 中可用?所以唯一的方法是使用 docstring 类型 - python 2 的类型提示?
    • mypy 适用于 Python 2:mypy.readthedocs.io/en/latest/python2.html
    • @user2235698 和 @Har -- 这是不正确的; typing 模块可作为 Python 2.7+ 的第 3 方库下载,因此类型提示在 Python 2 和 Python 3 中都可用。
    • 这很适合用:type打字,非常有用
    猜你喜欢
    • 2021-08-14
    • 2020-11-03
    • 2021-12-09
    • 2014-09-11
    • 2020-01-20
    • 2016-10-16
    相关资源
    最近更新 更多