shantanu rahut
shantanu rahut

Reputation: 329

How to use one class attribute of a class as a type inside another class in pydantic?

from pydantic import BaseModel
from typing import Optional

class A(BaseModel):
    a: int
    b: Optional[str]
    c: bool = False

class B(BaseModel):
    a: str
    b: Optional[str]
    c:  #I want to add the attribute "c" from class A as a type here 

How do I use attribute "c" from class A as a type inside class B?

Upvotes: 0

Views: 1585

Answers (2)

Prince
Prince

Reputation: 9

You should try this:

from pydantic import BaseModel
from typing import Optional, List

class A(BaseModel):
   a: int
   b: Optional[str]
   c: bool = False

class B(BaseModel):
   a: str
   b: Optional[str]
   c: List(A)

Upvotes: -1

Wizard.Ritvik
Wizard.Ritvik

Reputation: 11611

I guess you'd want to subclass from A like below (overriding the type annotations in A if needed):

from pydantic import BaseModel
from typing import Optional


class A(BaseModel):
    a: int
    b: Optional[str]
    c: bool = False

class B(A, BaseModel):
    a: str


print(B(a=123, c=True))
# a='123' b=None c=True

Upvotes: 3

Related Questions