我有一个只能返回的函数a,b或者c它们都是类型T。我想将这一事实包括在签名中,因为它们在功能上下文中具有特殊含义。我怎么做?
a
b
c
T
目前,我用这个
def fun(...) -> "a or b or c": #briefly explain the meaning of a, b and c in its docstring
那是正确的吗?
我知道我可以做到
def fun(...) -> T: #briefly explain the meaning of a, b and c in its docstring
但是正如我所说,我想在签名中表示该函数仅返回那些特定值。
from typing_extensions import Literal # from typing import Literal # Python 3.8 or higher def fun(b: int) -> Literal["a", "b", "c"]: if b == 0: return "a" if b == 1: return "b" return "d"
mypy能够将检出return "d"为无效语句:
return "d"
error: Incompatible return value type (got "Literal['d']", expected "Union[Literal['a'], Literal['b'], Literal['c']]")
多亏了PEP 586,将Literal是已经包含默认的Python 3.8typing模块。
Literal
typing