gpt4 book ai didi

python - 为仅返回一组特定值的函数键入提示

转载 作者:太空狗 更新时间:2023-10-29 21:30:49 25 4
gpt4 key购买 nike

我有一个只能返回 a 的函数, bc , 它们都是 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

但正如我所说,我想在签名中表达该函数仅返回那些特定值。

最佳答案

你可以用 literal types 做到这一点.

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" 检测为无效语句:

error: Incompatible return value type (got "Literal['d']",
expected "Union[Literal['a'], Literal['b'], Literal['c']]")

python 3.8

感谢 PEP 586 , Literalalready included默认情况下在 Python 3.8 typing 模块中。

关于python - 为仅返回一组特定值的函数键入提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39398138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com