Home > OS >  Pydantic to match Enum nested in Generic Models
Pydantic to match Enum nested in Generic Models

Time:08-05

I am struggling with Pydantic to parse Enumerate when it's nested in Generic Models.

class MyEnum(str, Enum):
    A = 'a',
    B = 'b',
    C = 'c'

enumT = TypeVar('enumT',bound=MyEnum)

class EnumContainer(GenericModel,Generic[enumT]):
    enum_value: enumT
    
containerT = TypeVar('containerT', bound=EnumContainer)

class OuterContainer(GenericModel,Generic[containerT]):
    container: containerT

class testEnumparsing(BaseModel):
    typer: OuterContainer[EnumContainer[MyEnum.B]]
    class Config:
        orm_mode = True

obj = testEnumparsing(
    typer= OuterContainer(
            container=EnumContainer(enum_value='a')
        )
)

parsed = testEnumparsing.from_orm(obj)
print(parsed)

Having the Generic models, how can I make an object evaluate to testEnumparsing only for a specific Enum value? In the example above, it should only coerce if the value passed was 'b'.

but typer: OuterContainer[EnumContainer[MyEnum.B]] doesnot seems to work.

CodePudding user response:

Use type Literal[MyEnum.B] for EnumContainer

class testEnumparsing(BaseModel):
    typer: OuterContainer[EnumContainer[Literal[MyEnum.B]]]

    class Config:
        orm_mode = True

Passes:

obj = testEnumparsing(
    typer=OuterContainer(
        container=EnumContainer(enum_value=MyEnum.B)
    )
)

Fails:

obj = testEnumparsing(
    typer=OuterContainer(
        container=EnumContainer(enum_value=MyEnum.A)
    )
)
  • Related