Sneha Tunga
Sneha Tunga

Reputation: 172

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

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"]]    

Upvotes: 9

Views: 7482

Answers (2)

Sneha Tunga
Sneha Tunga

Reputation: 172

I got an answer to this - Create a literal for both the lists, and then create a combined literal

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

SUPPORTED_TYPES = Literal[category1, category2]

Sorry: hadnt seen that monica answered the question

Upvotes: 1

user2357112
user2357112

Reputation: 280182

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.

Upvotes: 12

Related Questions