我想将方法的参数键入为一组有限的有效值之一。所以基本上,我希望有相当于以下最小示例的打字
:
valid_parameters = ["value", "other value"]
def typed_method(parameter):
if not parameter in valid_parameters:
raise ValueError("invalid parameter")
我已经检查了打字
,但我没有找到解决方案。也许我只是无法完全理解文档。有这样的解决办法吗?可以创建吗?
最佳答案
此功能刚刚在 Python 3.8 中引入:typing.Literal
。请参阅PEP 586了解详情。
示例:
def typed_method(parameter: Literal["value", "other value"]):
pass
关于Python 键入 : Given Set of Values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58521577/