1

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"]]    
Sneha Tunga
  • 82
  • 1
  • 8
  • 1
    "because I dont want mimetype to be of type typing.Tuple" - but it wouldn't be of type `typing.Tuple`. It'd be a literal type, exactly what you need. – user2357112 Feb 19 '22 at 11:04
  • Maybe you just got confused by the fact that the all caps are the other way around in the question you linked. – user2357112 Feb 19 '22 at 11:17

2 Answers2

3

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
0

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

Sneha Tunga
  • 82
  • 1
  • 8