我有一个参数,它是一个字符串列表。然而,我只想允许某些字符串,比如“hello”和“world”。如何正确地注解变量?下面是一个例子:
def foo(bar: List[str]): assert all(b in ["hello", "world"])
def foo(bar: List[str]):
assert all(b in ["hello", "world"])
我知道我可以使用Literal,但AFAIK这只适用于单个值。也就是说,Literal["hello", "world"]将允许bar是一个值为“hello”或“world”的字符串。但这是如何工作的名单?
Literal
Literal["hello", "world"]
bar
xkftehaa1#
Python的enum模块可以帮助你。我修改了你的代码如下-
enum
from typing import Listfrom enum import Enumclass HelloWorld(Enum): _hello = "hello" _world = "world"def foo(bar: List[HelloWorld]): assert all(b in [HelloWorld._hello, HelloWorld._world] for b in bar)
from typing import List
from enum import Enum
class HelloWorld(Enum):
_hello = "hello"
_world = "world"
def foo(bar: List[HelloWorld]):
assert all(b in [HelloWorld._hello, HelloWorld._world] for b in bar)
请查找键入Union和enum的参考资料
1条答案
按热度按时间xkftehaa1#
Python的
enum
模块可以帮助你。我修改了你的代码如下-请查找键入Union和enum的参考资料