Sunday 26 September 2021

Pydnatic: Define generic models

Step 1: Declare one or more typing.TypeVar instances to parameterize your model.

TypeX = TypeVar('TypeX')

Step 2: Declare a pydantic model that inherits from pydantic.generics.GenericModel and typing.Generic, and pass the TypeVar instances as parameters to typing.Generic.

 

Use the TypeVar instances as annotations where you want to replace them with other types or pydantic models.

 

class Point(GenericModel, Generic[TypeX]):
    x: TypeX

 

Find the below working application.

 

generic_model_1.py

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

TypeX = TypeVar('TypeX')

class Point(GenericModel, Generic[TypeX]):
    x: TypeX

point1 = Point[int](x=1)
point2 = Point[str](x='1')
print(point1)
print(point2)

 

Output

x=1
x='1'

 

Working with multiple generic arguments

Step 1: Define TypeVar instances.

TypeX = TypeVar('TypeX')
TypeY = TypeVar('TypeY')

  Step 2: Define a model by extending GenericModel and using the generic types.

 

class Point(GenericModel, Generic[TypeX, TypeY]):
    x: TypeX
    y: TypeY

Step 3: Define the object of type Point.

point1 = Point[int, int](x=1, y=2)

Find the below working application.

 

generic_model_2.py

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

TypeX = TypeVar('TypeX')
TypeY = TypeVar('TypeY')

class Point(GenericModel, Generic[TypeX, TypeY]):
    x: TypeX
    y: TypeY

point1 = Point[int, int](x=1, y=2)
point2 = Point[str, str](x='1', y='2')
print(point1)
print(point2)

Output

x=1 y=2
x='1' y='2'



 

Previous                                                    Next                                                    Home

No comments:

Post a Comment