let me describe the problem a bit more,
I have a setup like this,
in child_one.py
from pydantic import BaseModel
class BModel(BaseModel):
x: str
y: int
class B(A):
def __init__(self):
super().__init__(BModel)
in child_two.py
from pydantic import BaseModel
class CModel(BaseModel):
a: list
b: dict
class C(A)
def __init__(self):
super().__init__(CModel)
in parent.py
from .child_one import BModel
from .child_two import CModel
from typing import TypeVar, Union
T = TypeVar('T', Union[BModel, CModel])
class A:
def __init__(self, model: T):
self.model = model
def func(self, param: T):
pass
I want the param: T
to consider the T
as per what is passed in __init__
of the child classes.
So, if the
T
in model: T
, considers BModel
, then param also considers BModel
, and if the
T
in model: T
considers CModel
, then param also considers CModel
.
But the Union
does not work, it makes T
to consider BModel
for both the cases.
I use it with fastapi, to get the request body, based on what T
is, if we use BModel
then the request body would ask for a string and an int, if we use CModel
then the request body would ask for a list and a dict.
The other way is I write func
in both child_one.py and child_two.py, that is,
in child_two.py
class C(A)
def __init__(self):
super().__init__()
def func(self, param: CModel):
...
in child_one.py
class B(A):
def __init__(self):
super().__init__()
def func(self, param: BModel):
...
but I do not want to specify func
in both child files