2016-09-05 43 views
0

有誰知道如何爲類型提示編寫聯合?PyCharm:如何在pycharm中指定類型提示的工會

我做以下,但它沒有被PyCharm認可:

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

什麼是指定類型提示了工會的正確方法是什麼?

我爲此使用了python 2.7。

回答

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可能是因爲混淆因您的返回類型的額外括號,或者是因爲你忘了導入Union來自typing模塊。

+0

我正在使用python 2.7,我沒有訪問打字模塊,是一個僅適用於python 3的聯盟嗎? – Har

+1

@哈爾 - 你可以通過'pip install typing'在Python 2.7上安裝'typing'模塊。 'typing'模塊被添加到Python 3.5中的標準庫中,並且可以在Python 2.7和Python 3.2 - 3.4上作爲第三方庫進行安裝。 – Michael0x2a

1

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 
+0

這是否意味着基於PEP的類型提示僅在python 3中可用?所以唯一的方法是使用docstring type-type hinting for python 2? – Har

+1

mypy與Python 2一起工作:http://mypy.readthedocs.io/en/latest/python2.html –

+3

@ user2235698和@哈爾 - 這是不正確的; 'typing'模塊可以作爲Python 2.7+的第三方庫下載,因此類型提示可以在Python 2和Python 3中使用。 – Michael0x2a