Last active
November 14, 2023 15:05
-
-
Save cdddg/97690b2a68dc731e42884a14958b1074 to your computer and use it in GitHub Desktop.
Pydantic default values test in version 1.10
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from decimal import Decimal | |
from typing import Optional | |
from pydantic import BaseModel, root_validator | |
from pydantic.fields import SHAPE_SINGLETON, ModelField | |
class CustomBaseModel(BaseModel): | |
@staticmethod | |
def is_optional(field: ModelField): | |
if field.allow_none and (field.shape != SHAPE_SINGLETON or not field.sub_fields): | |
return True | |
return False | |
@root_validator(pre=True) | |
def set_default_value_with_optional_field(cls, values: dict): | |
for k, field in cls.__fields__.items(): | |
default = field.get_default() | |
if cls.is_optional(field) and default is not None: | |
v = values.pop(k, None) | |
values[k] = default if v is None else v | |
return values | |
class DefaultUser(BaseModel): | |
id: int | |
name: Optional[str] = 'kobe' | |
coin: Optional[int] = 100 | |
number: Optional[Decimal] = Decimal('0.1') | |
items: Optional[list[str]] = [] | |
class CustomUser(CustomBaseModel): | |
id: int | |
name: Optional[str] = 'kobe' | |
coin: Optional[int] = 100 | |
number: Optional[Decimal] = Decimal('0.1') | |
items: Optional[list[str]] = [] | |
print(DefaultUser(id=1)) | |
# >>> id=1 name='kobe' coin=100 number=Decimal('0.1') items=[] | |
print(CustomUser(id=1)) | |
# >>> id=1 name='kobe' coin=100 number=Decimal('0.1') items=[] | |
print(DefaultUser(id=1, name=None, coin=None, number=None, items=None)) | |
# >>> id=1 name=None coin=None number=None items=None | |
print(CustomUser(id=1, name=None, coin=None, number=None, items=None)) | |
# >>> id=1 name='kobe' coin=100 number=Decimal('0.1') items=[] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pydantic default values test in version 1.10.
Demonstrates how
DefaultUser
andCustomUser
handle not providedvalues versus
None
.DefaultUser
applies standard Pydantic behavior,while
CustomUser
uses a custom root validator to overrideNone
with defaults.