gpt4 book ai didi

字符串选项的 Python 3 类型提示

转载 作者:行者123 更新时间:2023-12-03 09:28:18 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Type hint for a function that returns only a specific set of values

(3 个回答)


2年前关闭。




假设,我有一个函数,其字符串参数对应于方法名称:

def func(method: str):
if method not in ('simple_method', 'some_other_method'):
raise ValueError('Unknown method')

我可以添加所有可能支持的选项(字符串)作为此参数的类型提示吗?例如,像这样的东西(由于没有输入 Str ,所以不起作用):
from typing import Str

def func(method: Str['simple_method', 'some_other_method']):
...

最佳答案

仅使用类型提示是不可能的,正确的方法应该是 enums像这样:

from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
一旦你有一个包含所有可能选择的枚举,你可以提示该函数以便只接受你的自定义枚举。更多信息 here
例子:
 from typing import NewType

Colors = NewType('Colors', Color)

关于字符串选项的 Python 3 类型提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58114837/

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