Home > Net >  How to set the default model to a variable if None was passed?
How to set the default model to a variable if None was passed?

Time:10-25

Can I make a default model in Pydantic if None is passed in the field?

I am new to pydantic and searched for relevant answers but could not find any. I have the following code,

from typing import Optional,List
from pydantic import BaseModel

class FieldInfo(BaseModel):
    value: Optional[str] = ""
    confidence: Optional[float] = -1.0


class UserInfo(BaseModel):
    first_name: Optional[FieldInfo]
    last_name: Optional[FieldInfo]

user_info = {"user":{"first_name":["john",0.98], "last_name":["doe",0.98]}}
user = UserInfo(**{k:{"value":v[0],"confidence":v[1]} for k,v in user_info["user"].items()})
print(user)

gives me

first_name=FieldInfo(value='john', confidence=0.98) last_name=FieldInfo(value='doe', confidence=0.98)

but if last_name is None i.e.

user_info = {"user":{"first_name":["john",0.98]}}
user = UserInfo(**{k:{"value":v[0],"confidence":v[1]} for k,v in user_info["user"].items()})
print(user)

I get

first_name=FieldInfo(value='john', confidence=0.98) last_name=None

How can i get it take the default value if there is no values is passed, like below

first_name=FieldInfo(value='john', confidence=0.98) last_name=FieldInfo(value='', confidence=-1.0)

CodePudding user response:

It should just include adding a default value in UserInfo.last_name like so:

from typing import Optional
from pydantic import BaseModel

class FieldInfo(BaseModel):
    value: Optional[str] = ""
    confidence: Optional[float] = -1.0


class UserInfo(BaseModel):
    first_name: Optional[FieldInfo]
    # Note I've added `= FieldInfo(...)` below
    last_name: Optional[FieldInfo] = FieldInfo(value='', confidence=-1.0)
  • Related