Home > database >  Pydantic inherit generic class
Pydantic inherit generic class

Time:03-31

New to python and pydantic, I come from a typescript background. I was wondering if you can inherit a generic class?

In typescript the code would be as follows

interface GenericInterface<T> {
  value: T
}

interface ExtendsGeneric<T> extends GenericInterface<T> {
  // inherit value from GenericInterface
  otherValue: string
}

const thing: ExtendsGeneric<Number> = {
  value: 1,
  otherValue: 'string'
}

What I have been trying is something along the lines of

#python3.9
from pydantic.generics import GenericModel
from typing import TypeVar
from typing import Generic

T = TypeVar("T", int, str)

class GenericField(GenericModel, Generic[T]):
    value: T

class ExtendsGenericField(GenericField[T]):
    otherValue: str

ExtendsGenericField[int](value=1, otherValue="other value")

And I get the error of TypeError: Too many parameters for ExtendsGenericField; actual 1, expected 0. This sort of checks out because in the Pydantic docs it explicitly states "In order to declare a generic model...Use the TypeVar instances as annotations where you will want to replace them..." The easy workaround is to make ExtendsGeneric inherit from GenericModel and have value in its own class definition, but I was trying to reuse classes.

Is inheriting a value from a generic class possible?

CodePudding user response:

Generics are a little weird in Python, and the problem is that ExtendsGenericField itself isn't declared as generic. To solve, just add Generic[T] as a super class of ExtendsGenericField:

from pydantic.generics import GenericModel
from typing import TypeVar
from typing import Generic

T = TypeVar("T", int, str)

class GenericField(GenericModel, Generic[T]):
    value: T

class ExtendsGenericField(GenericField[T], Generic[T]):
    otherValue: str

ExtendsGenericField[int](value=1, otherValue="other value")
  • Related