Answer the question
In order to leave comments, you need to log in
How to annotate the type of a class attribute to be overridden?
Let's say we have an abstract class:
import abc
from pydantic import BaseModel
class Abstract(abc.ABC):
context_class: ClassVar[Type['BaseModel']]
error: ClassVar[Type[Exception]]
def __init__(self, data: Dict) -> None:
self.context = self.context_class(**data)
@abc.abstractmethod
def process(self) -> None:
pass
class Context(BaseModel):
email: str
class Concrete(Abstract):
context_class = Context
def process(self) -> None:
print(self.context.email)
... error: "BaseModel" has no attribute "email"
Answer the question
In order to leave comments, you need to log in
Solution found:
import abc
from typing import ClassVar, Type, Dict, Generic, TypeVar
from pydantic import BaseModel
T = TypeVar('T', bound=BaseModel)
class Abstract(abc.ABC, Generic[T]):
context_class: ClassVar[Type[T]]
error: ClassVar[Type[Exception]]
def __init__(self, data: Dict) -> None:
self.context = self.context_class(**data)
@abc.abstractmethod
def process(self) -> None:
pass
class Context(BaseModel):
email: str
class Concrete(Abstract[Context]):
context_class = Context
def process(self) -> None:
print(self.context.email)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question