Last active
May 24, 2023 13:03
-
-
Save laurent-laporte-pro/2f7ca04f92c08b59ca084389b851756a to your computer and use it in GitHub Desktop.
Pydantic model with optional fields
This file contains hidden or 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 enum import Enum | |
from typing import Optional | |
import pydantic.main | |
from pydantic import Field, BaseModel | |
class AllOptionalMetaclass(pydantic.main.ModelMetaclass): | |
.... | |
class SizeEnum(str, Enum): | |
SMALL = "Small" | |
MEDIUM = "Medium" | |
LARGE = "Large" | |
class Product(BaseModel, metaclass=AllOptionalMetaclass): | |
name: str = Field(description="The name of the product") | |
price: Optional[float] = Field( | |
gt=0, | |
description="The price of the product (in euro)", | |
) | |
quantity: Optional[int] = Field( | |
1, | |
gt=0, | |
description="The available quantity of the product", | |
) | |
product_size: Optional[SizeEnum] = Field( | |
SizeEnum.SMALL, | |
description="The size of the product", | |
) | |
def foo(self, arg: str) -> str: | |
return self.name + arg | |
# Example d'utilisation sans argument | |
print(Product()) | |
# name=None price=None quantity=1 product_size=<SizeEnum.SMALL: 'Small'> | |
# Example d'utilisation avec explicitement la valeur None | |
print(Product(name="Car", quantity=None)) | |
# name='Car' price=None quantity=None product_size=<SizeEnum.SMALL: 'Small'> | |
# Example d'utilisation avec un paramètre invalide | |
print(Product(quantity=0)) | |
# Traceback (most recent call last): | |
# ... | |
# pydantic.error_wrappers.ValidationError: 1 validation error for Product | |
# quantity | |
# ensure this value is greater than 0 (type=value_error.number.not_gt; limit_value=0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment