Skip to content

Instantly share code, notes, and snippets.

@Isaac3N
Last active January 12, 2022 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Isaac3N/9926edfbd5424b8b9139f473e448ed46 to your computer and use it in GitHub Desktop.
Save Isaac3N/9926edfbd5424b8b9139f473e448ed46 to your computer and use it in GitHub Desktop.
Example of how to use pydantic
from pydantic import BaseModel
from typing import Optional #this is to enable more complex field types
from random import randrange #to import a random integer
class Product(BaseModel):
title: str
description: str
price: int
ratings: Optional[int] = None
published: Optional[bool]= True
id: Optional[int]= None
#The optional keyword is used to indicated that the field is not required to be filled. It is then given a default value
data = {
"title": "Iphone 13 pro max",
"description": "This is the latest Iphone from apple",
"price": 1000,
"ratings": 4.56,
"id": randrange(0, 100000000) #creates a random integer between 0 and 100000000
}
product = Product(**data) #to read the python dictionary
print(product)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment