2016-09-05 5 views
0

Wer weiß, wie eine Vereinigung für die Type Hinting zu schreiben?PyCharm: Wie angeben Gewerkschaften für Type Hinting in PyCharm

ich tue folgendes aber es wird nicht von PyCharm erkannt:

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

Was der richtige Weg, um eine Art Hauch Angabe für eine Union ist?

Ich verwende Python 2.7 für diese.

Antwort

1

Doing folgende Arbeiten für mich, in PyCharm (Version 2016.02.02):

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 kann, weil in Ihrem Rückgabetyp aufgrund des zusätzlichen Pars verwechselt werden, oder vielleicht, weil Sie Union zu importieren vergessen, aus dem typing Modul.

+0

ich verwende Python 2.7, ich habe nicht den Zugriff auf die Typisierung Modul, ist eine Union nur für Python 3? – Har

+1

@Har - Sie können das 'typing' Modul in Python 2.7 installieren, indem Sie' pip install tipping' ausführen. Das "typing" -Modul wurde der Standardbibliothek in Python 3.5 hinzugefügt und kann als eine 3rd-Party-Bibliothek auf Python 2.7 und Python 3.2 - 3.4 installiert werden. – Michael0x2a

1

Es gibt many ways Gewerkschaften für Type Hinting angeben.

In Python 2 und 3 können Sie die folgende verwenden:

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

In Python 3.5 typing Modul eingeführt wurde, so dass Sie eine der folgenden Optionen verwenden:

from typing import Union 

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

oder

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 

oder

from typing import Union 


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

Bedeutet dies, dass PEP-basierte Typhinweis nur in Python 3 verfügbar ist? Also ist der einzige Weg, Docstring Typ - Typhinweis für Python 2 zu verwenden? – Har

+1

mypy arbeitet mit Python 2: http://mypy.readthedocs.io/en/latest/python2.html –

+3

@ user2235698 und @Har - das ist falsch; Das 'typing' Modul ist als eine 3rd-Party-Bibliothek für Python 2.7+ verfügbar und folglich ist typing hinting sowohl in Python 2 als auch in Python 3 verfügbar. – Michael0x2a