Setting alias based on type of generic field

18 Views Asked by At

I'm building an object hierarchy to make conversion to and from XML easier. I have three classes, call them A, B and C. I also have D which looks like this:

from typing import List, TypeVar, Generic, Union
from pydantic import Field, BaseModel

P = TypeVar("P", bound=Union[A, B, C])

class D(BaseModel, Generic[P]):

    data: List[P] = Field(alias="Data")

This will work fine for holding the data, but the issue I'm having is that I would like to set alias to a different value, depending on what P is. For example, I'd want it to be DataA if the class's type is D[A].

I'm bumping up against the limits of my understanding of Python's typing library and Pydantic here so I'm not entirely sure this is possible. Perhaps I need to use a factory instead? If anyone has an idea of how this should be done, I'd really appreciate it.

0

There are 0 best solutions below