如何从 python 中的多个值列表创建 typing.Literal

How to create typing.Literal from multiple lists of values in python

我有两个列表。我想使用这两个列表

创建一个 Literal
category1 = ["image/jpeg", "image/png"]
category2 = ["application/pdf"]

SUPPORTED_TYPES = typing.Literal[category1 + category2]

有什么办法吗?

我看到了问题 但这对我的用例不起作用,因为我不希望 mimetypetyping.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"]]    

使用与您链接的问题相同的技术:从文字类型构建列表,而不是相反:

SUPPORTED_IMAGE_TYPES = typing.Literal["image/jpeg", "image/png"]
SUPPORTED_OTHER_TYPES = typing.Literal["application/pdf"]

SUPPORTED_TYPES = typing.Literal[SUPPORTED_IMAGE_TYPES, SUPPORTED_OTHER_TYPES]

category1 = list(typing.get_args(SUPPORTED_IMAGE_TYPES))
category2 = list(typing.get_args(SUPPORTED_OTHER_TYPES))

其他答案中唯一未涵盖的部分是 SUPPORTED_TYPES = typing.Literal[SUPPORTED_IMAGE_TYPES, SUPPORTED_OTHER_TYPES],即 yeah, you can do that。它等同于您对 SUPPORTED_TYPES.

的原始定义

我得到了这个答案 - 为两个列表创建一个文字,然后创建一个组合文字

category1 = Literal["image/jpeg", "image/png"]
category2 = Literal["application/pdf"]

SUPPORTED_TYPES = Literal[category1, category2]

抱歉:没看到莫妮卡回答了问题