Here’s my setup simplified:
from abc import ABC
from typing import TypeVar
from pydantic import BaseModel
_M = TypeVar("_M", bound=BaseModel)
class A(BaseModel):
a = 1
b = 2
c = 3
class Base(ABC):
cfg_model: type[_M]
def __init__(self):
self.cfg = self.cfg_model()
class ChildA(Base):
cfg_model = A
def run(self):
self.cfg_model # (variable) model_class: type[_M]
self.cfg # (variable) cfg: _M
# pylance fails to detect properties in `self.cfg`
self.cfg.a
self.cfg.b
self.cfg.c
The idea is that there are multiple classes extending the base abstract class, each having it’s own config model.
But i can’t seem to figure out how to make pylance (i’m using Visual Studio Code) correctly typecheck self.cfg
in ChildA
‘s run
method as A
.
UPD: Turning Base
into generic class helped:
from abc import ABC
from typing import TypeVar
from pydantic import BaseModel
_M = TypeVar("_M", bound=BaseModel)
class A(BaseModel):
a = 1
b = 2
c = 3
class Base(ABC, Generic[_M]):
cfg_model: type[_M]
def __init__(self):
self.cfg = self.cfg_model()
class ChildA(Base[A]):
cfg_model = A
def run(self):
self.cfg_model # (variable) model_class: type[A]
self.cfg # (variable) cfg: A
# all properties are correctly typechecked
self.cfg.a
self.cfg.b
self.cfg.c
However, it irks me that i need to provide the Model name twice (in class argument and in class variable). Can this be avoided somehow?
5