I have a function that can only return a
, b
or c
, all of them are of type 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
但正如我所说,我想在签名中表达函数只返回那些特定的值。
原文由 Copperfield 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用 文字类型 来做到这一点。
mypy 能够将
return "d"
检测为无效语句:Python 3.8
感谢 PEP 586 ,
Literal
已经默认包含 在 Python 3.8typing
模块中。