如何在python中使用特定值键入annotate List参数

mwg9r5ms  于 2023-04-28  发布在  Python
关注(0)|答案(1)|浏览(122)

我有一个参数,它是一个字符串列表。然而,我只想允许某些字符串,比如“hello”和“world”。如何正确地注解变量?
下面是一个例子:

  1. def foo(bar: List[str]):
  2. assert all(b in ["hello", "world"])

我知道我可以使用Literal,但AFAIK这只适用于单个值。也就是说,Literal["hello", "world"]将允许bar是一个值为“hello”或“world”的字符串。但这是如何工作的名单?

xkftehaa

xkftehaa1#

Python的enum模块可以帮助你。我修改了你的代码如下-

  1. from typing import List
  2. from enum import Enum
  3. class HelloWorld(Enum):
  4. _hello = "hello"
  5. _world = "world"
  6. def foo(bar: List[HelloWorld]):
  7. assert all(b in [HelloWorld._hello, HelloWorld._world] for b in bar)

请查找键入Union和enum的参考资料

相关问题