如何在Python中为仅含特定值的List参数添加类型注解
为列表参数添加特定字符串值的类型注解
你可以直接结合List(Python 3.9+也可用标准库的list)与Literal来实现这个需求,把Literal作为列表的类型参数,就能明确标注列表中的每个元素必须是指定的字面量值。
修改后的示例代码
from typing import List, Literal def foo(bar: List[Literal["hello", "world"]]): # 运行时校验可保留,作为类型注解的补充(类型注解本身不具备运行时校验能力) assert all(b in {"hello", "world"} for b in bar), "列表元素只能是'hello'或'world'"
说明
- 类型注解
List[Literal["hello", "world"]]会告诉mypy等类型检查工具:bar必须是一个列表,且其中每一个元素只能是"hello"或"world"。 - 如果你使用的是Python 3.9及以上版本,可以用标准库原生的
list替代typing.List,写法更简洁:from typing import Literal def foo(bar: list[Literal["hello", "world"]]): assert all(b in {"hello", "world"} for b in bar), "列表元素只能是'hello'或'world'"
内容的提问来源于stack exchange,提问作者timbmg
相关产品推荐
相关产品推荐

