I have two lists. I want to create a Literal using both these lists
category1 = ["image/jpeg", "image/png"]
category2 = ["application/pdf"]
SUPPORTED_TYPES = typing.Literal[category1 + category2]
Is there any way to do this?
I have seen the question typing: Dynamically Create Literal Alias from List of Valid Values but this doesnt work for my use case because I dont want mimetype to be of type typing.Tuple.
I will be using the Literal in a function –
def process_file(filename: str, mimetype: SUPPORTED_TYPES)
What I have tried –
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"]]
>Solution :
Use the same technique as in the question you linked: build the lists from the literal types, instead of the other way around:
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))
The only part of this that wasn’t already covered in the other answer is SUPPORTED_TYPES = typing.Literal[SUPPORTED_IMAGE_TYPES, SUPPORTED_OTHER_TYPES], which, yeah, you can do that. It’s equivalent to your original definition of SUPPORTED_TYPES.