Can I have a variable number of types on Union in Python?

Viewed 96

I have a structure like this:

from enum import Enum

class MainEnum(str, Enum):
    A = "AA"
    B = "BB"
    ...

class ChildAEnum(str, Enum):
    C = "CC"
    D = "DD"

class ChildBEnum(str, Enum):
    E = "EE"
    F = "FF"

...

child_mapping = {
    MainEnum.A: ChildAEnum
    MainEnum.B: ChildBEnum
    ...
}

Where each Enum on the MainEnum has another Enum associated to it and indicated by the child_mapping map.

I want to have a Union typehint that can be any one of the values from child_mapping. I don't know if it's relevant but I'm using pydantic and I want this for automatic validation of the field.

Manually, it would be exactly:

class Something(BaseModel):
   some_child: Union[ChildAEnum, ChildBEnum]

But I want to be able to just add another key-value pair to child_mapping and have it be automatically recognized by the Union.

I tried the following:

class Something(BaseModel):
    some_child: Union[*list(child_mapping.values())]

list(child_mapping.values()) successfully gets me a list of the types I want to use, but the unpack doesn't seem to be working

Am I even able to do this?

1 Answers

Writing about the problem helped me think about it. The solution is, instead of converting the child_mapping.values() to a list, converting it to a tuple.

So the solution is:

class Something(BaseModel):
    some_child: Union[tuple(child_mapping.values())]
Related