有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