【发布时间】:2022-02-19 19:20:08
【问题描述】:
我有两个列表。我想使用这两个列表创建一个Literal
category1 = ["image/jpeg", "image/png"]
category2 = ["application/pdf"]
SUPPORTED_TYPES = typing.Literal[category1 + category2]
有什么办法吗?
我看到了typing: Dynamically Create Literal Alias from List of Valid Values 的问题,但这不适用于我的用例,因为我不希望mimetype 的类型为typing.Tuple。
我将在函数中使用Literal -
def process_file(filename: str, mimetype: SUPPORTED_TYPES)
我尝试过的-
supported_types_list = category1 + category2
SUPPORTED_TYPES = Literal[supported_types_list]
SUPPORTED_TYPES = Literal[*supported_types_list]
# this gives 2 different literals, rather i want only 1 literal
SUPPORTED_TYPES = Union[Literal["image/jpeg", "image/png"], Literal["application/pdf"]]
【问题讨论】:
-
"因为我不希望 mimetype 的类型为 typing.Tuple" - 但它不会是
typing.Tuple类型。这将是一种文字类型,正是您所需要的。 -
也许您只是对所有大写字母在您链接的问题中相反这一事实感到困惑。
标签: python type-hinting python-typing