You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Share several ways of writing parameter selection values, which may be useful
1、what goes in and what goes out
from typing import Literal
from pydantic import BaseModel
class User(BaseModel):
name: str
gender: Literal["female", "male", "other"]
user = User(name="dylan", gender="female")
print(user.dict()) # {'name': 'dylan', 'gender': 'female'}
2、The input and output are inconsistent, and the output can be customized (simple)
from enum import IntEnum
from pydantic import BaseModel, validator
class GenderEnum(IntEnum):
female = 0
male = 1
other = 2
class User(BaseModel):
name: str
gender: GenderEnum
@validator('gender')
def validate_gender(cls, v):
return GenderEnum(v).name
user = User(name="dylan", gender=0)
print(user.dict()) # {'name': 'dylan', 'gender': 'female'}
3、Input and output are inconsistent, output can be customized (complex)
from enum import Enum
from pydantic import BaseModel, root_validator
class Gender(str, Enum):
female = "it's a female"
male = "it's a male"
other = "it's a other"
class User(BaseModel):
name: str
gender: str
@root_validator(pre=True)
def map_enums(cls, values):
gender = values.get("gender")
if gender:
try:
values["gender"] = Gender[gender].value
except Exception:
raise ValueError(f"Invalid value for gender: {gender}")
return values
user = User(name="dylan", gender="female")
print(user.dict()) # {'name': 'dylan', 'gender': "it's a female"}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Share several ways of writing parameter selection values, which may be useful
1、what goes in and what goes out
2、The input and output are inconsistent, and the output can be customized (simple)
3、Input and output are inconsistent, output can be customized (complex)
Beta Was this translation helpful? Give feedback.
All reactions