Python - Passing enum set to Literal

82 Views Asked by At

I have a question about this construct:

from enum import Enum
from typing import Literal

class Fruit(Enum):
    Apple = "apple"
    Bannana = "bananna"
    Watermelon = "watermelon"

top_fruits = {
    Fruit.Watermelon,
    Fruit.Bannana
}

top_fruits_literal = Literal[*top_fruits]

VSCode is highlighting *top_fruits as "Unpacked arguments cannot be used in type argument lists", but the code works just fine.

What am I missing, is it bad idea creating Literal like this? Is there anything to change to do it "right way"?

2

There are 2 best solutions below

4
AKX On

It works because the Python interpreter can run that code just fine. The Python interpreter doesn't do type checking though.

However, type checkers aren't Python interpreters, and they're not smart enough to run it - which is what VSCode is saying.

3
meghna sinha On

You actually do not need to give * for a list,

top_frutis_literal = Literal[top_fruits]

This is good enough and that is why you are getting that error in Visual Studio. Although there is no error from Python.